Skip to content

ValeventArray

Notes

non-binned EVAs have multiple timeseries as abscissa binned EVAs only have a single timeseries as abscissa

ISASA = Irregularly Sampled AnalogSignalArray

eva - not callable - fully binnable --> beva

beva - callable --> veva (really ISASA) - binnable - castable to ASA and back

veva - not callable - somewhat binnable --> bveva - make stateful --> sveva - .data; .values

bveva - callable --> veva (not exactly an ISASA anymore, due to each signal being ND) - castable to beva (2d matrix, instead of list of 2d matrices); not complete!

sveva - callable --> veva - somewhat binnable --> bveva - .data; .values; .states

Remarks: I planned on having a list of arrays, and a list of timeseries for the ValueEventArrays.

ValueEventArrays have data structure nSeries : nEvents x nValues [(i, j, k) --> i: j=f(i), k] BinnedValueEventArrays have data structure nSeries x nBins x nValues [(i, j, k) --> i x j x k] and each of these structures are wrapped in intervals[data] pseudo encapsulation

BaseValueEventArray (ABC) --- veva (base) --- bveva (base) --- sveva (veva)

BaseValueEventArray

Bases: ABC

Base class for ValueEventArray and BinnedValueEventArray.

Source code in nelpy/core/_valeventarray.py
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
370
371
372
373
374
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
class BaseValueEventArray(ABC):
    """Base class for ValueEventArray and BinnedValueEventArray."""

    __aliases__ = {}
    __attributes__ = ["_fs", "_series_ids"]

    def __init__(
        self,
        *,
        fs=None,
        series_ids=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 = ItemGetter_loc(self)
            self.iloc = ItemGetter_iloc(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

        self.series_ids = series_ids

        self.loc = ItemGetter_loc(self)
        self.iloc = ItemGetter_iloc(self)

    def __renew__(self):
        """Re-attach slicers and indexers."""
        self.loc = ItemGetter_loc(self)
        self.iloc = ItemGetter_iloc(self)

    def __repr__(self):
        address_str = " at " + str(hex(id(self)))
        return "<BaseValueEventArray" + 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_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.
        """
        return

    @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

    @abstractmethod
    def n_values(self):
        """(int) The number of values associated with each event 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

    def _copy_without_data(self):
        """Return a copy of self, without event datas."""
        out = copy.copy(self)  # shallow copy
        out._data = None
        out = copy.deepcopy(
            out
        )  # just to be on the safe side, but at least now we are not copying the data!
        return out

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

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

    @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, 0] < first:
                first = series[0, 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, 0] > last:
                last = series[-1, 0]
        return last

    @series_ids.setter
    def series_ids(self, val):
        if val is None:
            self._series_ids = None
            return

        if len(val) != self.n_series:
            raise TypeError("series_ids must be of length n_series")

        # Convert to list of integers, handling various input types
        try:
            series_ids = []
            for item in val:
                if hasattr(item, "item") and item.size == 1:
                    # Handle numpy scalars
                    series_ids.append(int(item.item()))
                elif hasattr(item, "__int__") and not hasattr(item, "__len__"):
                    # Handle other numeric types (but not arrays)
                    series_ids.append(int(item))
                elif hasattr(item, "__len__") and len(item) == 1:
                    # Handle single-element arrays/lists
                    series_ids.append(int(item[0]))
                else:
                    raise TypeError(
                        f"Cannot convert {type(item)} with shape {getattr(item, 'shape', 'unknown')} to int"
                    )

            # Check for duplicates
            if len(set(series_ids)) < len(series_ids):
                raise TypeError("duplicate series_ids are not allowed")

            self._series_ids = series_ids
        except (TypeError, ValueError) as e:
            raise TypeError(f"series_ids must be int-like: {e}")

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

    @support.setter
    def support(self, val):
        """(nelpy.IntervalArray) The support of the underlying 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._data = self._restrict_to_interval_array_fast(
            intervalarray=self._abscissa.support, data=self.data, copyover=True
        )

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

    @domain.setter
    def domain(self, val):
        """(nelpy.IntervalArray) The domain of the underlying 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._data = self._restrict_to_interval_array_fast(
            intervalarray=self._abscissa.support, data=self.data, copyover=True
        )

    @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)

    @staticmethod
    def _standardize_kwargs(**kwargs):
        """Provide support for easier ValueEventArray keyword arguments.

        kwarg: time <==> timestamps <==> abscissa_vals <==> events
        kwarg: data <==> values <==> marks

        Examples
        --------
        veva = nel.ValueEventArray(time=..., )
        veva = nel.ValueEventArray(timestamps=..., )
        veva = nel.ValueEventArray(abscissa_vals=..., data=... )
        veva = nel.ValueEventArray(events=..., values=... )
        """

        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

        abscissa_vals = kwargs.pop("abscissa_vals", None)
        timestamps = kwargs.pop("timestamps", None)
        time = kwargs.pop("time", None)
        events = kwargs.pop("events", None)
        data = kwargs.pop("data", None)
        values = kwargs.pop("values", None)
        marks = kwargs.pop("marks", None)

        # only one of the above, else raise exception
        events = only_one_of(abscissa_vals, timestamps, time, events)
        values = only_one_of(data, values, marks)

        if events is not None:
            kwargs["events"] = events

        if values is not None:
            kwargs["values"] = values

        return kwargs

data property

Event datas in seconds.

domain property writable

(nelpy.IntervalArray) The domain of the underlying EventArray.

first_event property

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

fs property writable

(float) Sampling rate.

isempty property

(bool) Empty EventArray.

label property writable

Label pertaining to the source of the event series.

last_event property

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

n_series property

(int) The number of series.

series_ids property writable

Unit IDs contained in the BaseEventArray.

support property writable

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

copy()

Returns a copy of the EventArray.

Source code in nelpy/core/_valeventarray.py
397
398
399
400
401
def copy(self):
    """Returns a copy of the EventArray."""
    newcopy = copy.deepcopy(self)
    newcopy.__renew__()
    return newcopy

n_values() abstractmethod

(int) The number of values associated with each event series.

Source code in nelpy/core/_valeventarray.py
371
372
373
374
@abstractmethod
def n_values(self):
    """(int) The number of values associated with each event 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_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/_valeventarray.py
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
@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_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.
    """
    return

BinnedValueEventArray

Bases: BaseValueEventArray

A binned representation of ValueEventArray data.

This class creates a time-binned version of a ValueEventArray by aggregating event values within specified time bins. For each support interval, bins are defined globally (not per-series) using np.linspace as in BinnedEventArray. All series use the same bins for a given interval.

Parameters:

Name Type Description Default
vea ValueEventArray

The source ValueEventArray to be binned.

required
ds float

Bin size in seconds. Bins are created with left-inclusive, right-exclusive boundaries (e.g., [t, t+ds)).

required
method str or callable

Aggregation method for combining values within each bin: - "sum": Sum all values in the bin - "mean": Average of all values in the bin - "median": Median of all values in the bin - "min": Minimum value in the bin - "max": Maximum value in the bin - callable: Custom aggregation function that takes an array and returns a scalar

"mean"

Attributes:

Name Type Description
vea ValueEventArray

The original ValueEventArray used to create this binned version.

ds float

The bin size in seconds.

method str or callable

The aggregation method used for binning.

data ndarray

Binned data array of shape (n_series, n_bins, n_values) where: - n_series: Number of event series - n_bins: Total number of bins across all intervals - n_values: Number of values per event

bins ndarray

Array of bin edges used for binning.

bin_centers ndarray

Array of bin center times.

n_series int

Number of event series.

n_bins int

Total number of bins.

n_values int

Number of values per event.

fs float or None

Sampling frequency (inherited from source ValueEventArray).

support IntervalArray

Support intervals (inherited from source ValueEventArray).

Notes
  • Binning is performed per-series, with each series having its own bin boundaries starting from its minimum event time within each interval.
  • Bins use left-inclusive, right-exclusive boundaries [t, t+ds).
  • Events outside the support intervals are ignored.
  • Empty bins are filled with NaN values.
  • The resulting data maintains the same number of series and values as the original ValueEventArray.

Examples:

>>> import nelpy as nel
>>> events = [[0.1, 0.5, 1.0], [0.2, 0.6, 1.2]]
>>> values = [[1, 2, 3], [4, 5, 6]]
>>> vea = nel.ValueEventArray(events=events, values=values, fs=10)
>>> bvea = nel.BinnedValueEventArray(vea, ds=0.5, method="sum")
>>> print(bvea.data.shape)  # (2, n_bins, 1)
>>> print(bvea.bin_centers)  # Array of bin center times
Source code in nelpy/core/_valeventarray.py
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
2253
2254
2255
2256
2257
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
2434
2435
2436
2437
2438
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
class BinnedValueEventArray(BaseValueEventArray):
    """A binned representation of ValueEventArray data.

    This class creates a time-binned version of a ValueEventArray by aggregating
    event values within specified time bins. For each support interval, bins are
    defined globally (not per-series) using np.linspace as in BinnedEventArray.
    All series use the same bins for a given interval.

    Parameters
    ----------
    vea : ValueEventArray
        The source ValueEventArray to be binned.
    ds : float
        Bin size in seconds. Bins are created with left-inclusive, right-exclusive
        boundaries (e.g., [t, t+ds)).
    method : str or callable, default="mean"
        Aggregation method for combining values within each bin:
        - "sum": Sum all values in the bin
        - "mean": Average of all values in the bin
        - "median": Median of all values in the bin
        - "min": Minimum value in the bin
        - "max": Maximum value in the bin
        - callable: Custom aggregation function that takes an array and returns a scalar

    Attributes
    ----------
    vea : ValueEventArray
        The original ValueEventArray used to create this binned version.
    ds : float
        The bin size in seconds.
    method : str or callable
        The aggregation method used for binning.
    data : np.ndarray
        Binned data array of shape (n_series, n_bins, n_values) where:
        - n_series: Number of event series
        - n_bins: Total number of bins across all intervals
        - n_values: Number of values per event
    bins : np.ndarray
        Array of bin edges used for binning.
    bin_centers : np.ndarray
        Array of bin center times.
    n_series : int
        Number of event series.
    n_bins : int
        Total number of bins.
    n_values : int
        Number of values per event.
    fs : float or None
        Sampling frequency (inherited from source ValueEventArray).
    support : IntervalArray
        Support intervals (inherited from source ValueEventArray).

    Notes
    -----
    - Binning is performed per-series, with each series having its own bin
      boundaries starting from its minimum event time within each interval.
    - Bins use left-inclusive, right-exclusive boundaries [t, t+ds).
    - Events outside the support intervals are ignored.
    - Empty bins are filled with NaN values.
    - The resulting data maintains the same number of series and values as
      the original ValueEventArray.

    Examples
    --------
    >>> import nelpy as nel
    >>> events = [[0.1, 0.5, 1.0], [0.2, 0.6, 1.2]]
    >>> values = [[1, 2, 3], [4, 5, 6]]
    >>> vea = nel.ValueEventArray(events=events, values=values, fs=10)
    >>> bvea = nel.BinnedValueEventArray(vea, ds=0.5, method="sum")
    >>> print(bvea.data.shape)  # (2, n_bins, 1)
    >>> print(bvea.bin_centers)  # Array of bin center times
    """

    def __init__(self, vea, ds, method="mean"):
        # Set _data to a placeholder with the correct number of series and values
        n_series = vea.n_series
        n_values = (
            max(vea.n_values)
            if hasattr(vea, "n_values") and len(vea.n_values) > 0
            else 1
        )
        self._data = np.empty((n_series, 0, n_values))
        # Call base class constructor with metadata from vea, but don't copy series_ids
        super().__init__(
            fs=getattr(vea, "fs", None),
            series_ids=None,  # Let the base class handle default series_ids
            abscissa=getattr(vea, "_abscissa", None),
            ordinate=getattr(vea, "_ordinate", None),
            empty=False,
        )
        self.vea = vea
        self.ds = ds
        self.method = method
        self._bin()

    def _bin(self):
        """Perform binning operation on the ValueEventArray data, matching BinnedEventArray logic.

        For each support interval, bins are defined globally (not per-series) using np.linspace as in BinnedEventArray.
        All series use the same bins for a given interval. np.histogram is used for each value column for each series.
        Aggregation is performed using the specified method (sum, mean, etc.).
        """
        support = getattr(self.vea, "support", None)
        if support is None:
            # Fallback: use all events if no support is defined
            all_events = np.concatenate([np.asarray(ev) for ev in self.vea.events])
            if all_events.size == 0:
                self._data = np.zeros((self.vea.n_series, 0, self.vea.n_values[0]))
                self._bins = np.array([])
                self._bin_centers = np.array([])
                return
            tmin = np.min(all_events)
            tmax = np.max(all_events)
            intervals = [(tmin, tmax)]
        else:
            intervals = list(zip(support.starts, support.stops))

        n_series = self.vea.n_series
        n_values = max(self.vea.n_values)
        all_binned = []
        all_bins = []
        all_bin_centers = []

        if isinstance(self.method, str):
            method_str = self.method
            if method_str in ("sum", "mean", "min", "max", "median"):
                use_numba = True
            else:
                use_numba = False
        elif callable(self.method):
            method_str = None
            use_numba = False
        else:
            raise ValueError("method must be a string or callable")

        for start, stop in intervals:
            interval_length = stop - start
            if interval_length < self.ds:
                continue
            n_bins = int(np.floor(interval_length / self.ds))
            bins = np.linspace(start, start + n_bins * self.ds, n_bins + 1)
            bin_centers = bins[:-1] + (self.ds / 2)
            binned = np.full((n_series, n_bins, n_values), np.nan)

            if use_numba and n_values == 1:
                # Convert to numba.typed.List to avoid reflected list warning
                try:
                    events_list = NumbaList()
                    for ev in self.vea.events:
                        events_list.append(np.asarray(ev))
                    values_list = NumbaList()
                    for val in self.vea.values:
                        values_list.append(np.asarray(val))
                except Exception:
                    # Fallback to regular list if numba.typed.List is not available
                    events_list = [np.asarray(ev) for ev in self.vea.events]
                    values_list = [np.asarray(val) for val in self.vea.values]
                binned_agg = _bin_ragged_agg_numba(
                    events_list, values_list, bins, method_str
                )
                binned[:, :, 0] = binned_agg
            else:
                for i, (ev, val) in enumerate(zip(self.vea.events, self.vea.values)):
                    ev = np.asarray(ev)
                    val = np.asarray(val)
                    mask_interval = (ev >= start) & (ev < stop)
                    ev_in = ev[mask_interval]
                    val_in = val[mask_interval]
                    if ev_in.size == 0:
                        continue
                    for v in range(n_values):
                        if val_in.ndim == 1:
                            vals = val_in
                        else:
                            vals = val_in[:, v]
                        if method_str == "sum":
                            hist, _ = np.histogram(ev_in, bins=bins, weights=vals)
                            binned[i, :, v] = hist
                        else:
                            inds = np.digitize(ev_in, bins, right=False) - 1
                            for b in range(n_bins):
                                vals_in_bin = vals[inds == b]
                                if vals_in_bin.size > 0:
                                    if method_str == "mean":
                                        binned[i, b, v] = np.mean(vals_in_bin)
                                    elif method_str == "min":
                                        binned[i, b, v] = np.min(vals_in_bin)
                                    elif method_str == "max":
                                        binned[i, b, v] = np.max(vals_in_bin)
                                    elif method_str == "median":
                                        binned[i, b, v] = np.median(vals_in_bin)
                                    else:
                                        binned[i, b, v] = self.method(vals_in_bin)
            all_binned.append(binned)
            all_bins.append(bins)
            all_bin_centers.append(bin_centers)

        if all_binned:
            self._data = np.concatenate(all_binned, axis=1)
            self._bins = np.concatenate(
                [b[:-1] for b in all_bins] + [all_bins[-1][-1:]]
            )
            self._bin_centers = np.concatenate(all_bin_centers)
        else:
            self._data = np.zeros((n_series, 0, n_values))
            self._bins = np.array([])
            self._bin_centers = np.array([])

    @property
    def data(self):
        return self._data

    @property
    def bins(self):
        return self._bins

    @property
    def bin_centers(self):
        return self._bin_centers

    def __repr__(self):
        return f"<BinnedValueEventArray: {self.n_series} series, {self.n_bins} bins, {self.n_values} values, ds={self.ds}>"

    def __getitem__(self, idx):
        # Slicing by IntervalArray/EpochArray
        if hasattr(idx, "starts") and hasattr(idx, "stops"):
            mask = np.zeros_like(self.bin_centers, dtype=bool)
            for start, stop in zip(idx.starts, idx.stops):
                mask |= (self.bin_centers >= start) & (self.bin_centers < stop)
            new_obj = copy.copy(self)
            new_obj._data = self.data[:, mask, :]
            # Adjust bins and bin_centers
            # bins: keep edges that bracket the selected bin_centers
            bin_indices = np.where(mask)[0]
            if len(bin_indices) == 0:
                new_obj._bins = np.array([])
                new_obj._bin_centers = np.array([])
            else:
                new_obj._bins = self.bins[bin_indices[0] : bin_indices[-1] + 2]
                new_obj._bin_centers = self.bin_centers[mask]
            return new_obj
        else:
            raise NotImplementedError(
                "Only slicing by IntervalArray/EpochArray is supported."
            )

    @property
    def n_series(self):
        return self.data.shape[0]

    @property
    def n_bins(self):
        return self.data.shape[1]

    @property
    def n_values(self):
        return self.data.shape[2]

    @property
    def fs(self):
        return getattr(self, "_fs", None)

    @fs.setter
    def fs(self, value):
        self._fs = value

    @property
    def support(self):
        return getattr(self.vea, "support", None)

    def partition(self, ds=None, n_intervals=None):
        """Returns a BinnedValueEventArray 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 : BinnedValueEventArray
            BinnedValueEventArray that has been partitioned.
        """
        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

    @staticmethod
    def _to_2d_array(arr):
        """Convert array to 2D numpy array, handling object arrays properly."""
        if isinstance(arr, np.ndarray) and arr.dtype == object:
            # Handle object arrays by extracting the actual data
            if arr.size == 1:
                # Single element object array
                return np.atleast_2d(arr[0])
            else:
                # Multiple element object array - concatenate
                flattened = []
                for item in arr:
                    if isinstance(item, np.ndarray):
                        flattened.append(item)
                    else:
                        flattened.append(np.array(item))
                if flattened:
                    return np.vstack(flattened)
                else:
                    return np.array([]).reshape(0, 0)
        else:
            return np.atleast_2d(arr)

    def smooth(
        self, *, sigma=None, inplace=False, truncate=None, within_intervals=False
    ):
        """Smooth BinnedValueEventArray by convolving with a Gaussian kernel.

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

        Smoothing is applied within each interval by default.

        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, optional
            If True the data will be replaced with the smoothed data. Default is False.
        within_intervals : bool, optional
            If True, smooth within each interval. If False, smooth across intervals. Default is False.

        Returns
        -------
        out : BinnedValueEventArray
            New BinnedValueEventArray with smoothed data.
        """
        from .. import utils  # local import to avoid circular import

        if truncate is None:
            truncate = 4
        if sigma is None:
            sigma = 0.01  # 10 ms default
        fs = 1 / self.ds if self.ds else None
        return utils.gaussian_filter(
            self,
            fs=fs,
            sigma=sigma,
            truncate=truncate,
            inplace=inplace,
            within_intervals=within_intervals,
        )

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

    @property
    def lengths(self):
        """Lengths of contiguous segments, in number of bins."""
        if (
            self.n_bins == 0
            or self.support is None
            or getattr(self.support, "isempty", False)
        ):
            return 0
        # Each interval: count how many bin_centers fall within it
        lengths = []
        for start, stop in zip(self.support.starts, self.support.stops):
            mask = (self.bin_centers >= start) & (self.bin_centers < stop)
            lengths.append(np.sum(mask))
        return np.array(lengths)

lengths property

Lengths of contiguous segments, in number of bins.

partition(ds=None, n_intervals=None)

Returns a BinnedValueEventArray 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 BinnedValueEventArray

BinnedValueEventArray that has been partitioned.

Source code in nelpy/core/_valeventarray.py
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
def partition(self, ds=None, n_intervals=None):
    """Returns a BinnedValueEventArray 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 : BinnedValueEventArray
        BinnedValueEventArray that has been partitioned.
    """
    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

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

Smooth BinnedValueEventArray by convolving with a Gaussian kernel.

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

Smoothing is applied within each interval by default.

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
within_intervals bool

If True, smooth within each interval. If False, smooth across intervals. Default is False.

False

Returns:

Name Type Description
out BinnedValueEventArray

New BinnedValueEventArray with smoothed data.

Source code in nelpy/core/_valeventarray.py
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
def smooth(
    self, *, sigma=None, inplace=False, truncate=None, within_intervals=False
):
    """Smooth BinnedValueEventArray by convolving with a Gaussian kernel.

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

    Smoothing is applied within each interval by default.

    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, optional
        If True the data will be replaced with the smoothed data. Default is False.
    within_intervals : bool, optional
        If True, smooth within each interval. If False, smooth across intervals. Default is False.

    Returns
    -------
    out : BinnedValueEventArray
        New BinnedValueEventArray with smoothed data.
    """
    from .. import utils  # local import to avoid circular import

    if truncate is None:
        truncate = 4
    if sigma is None:
        sigma = 0.01  # 10 ms default
    fs = 1 / self.ds if self.ds else None
    return utils.gaussian_filter(
        self,
        fs=fs,
        sigma=sigma,
        truncate=truncate,
        inplace=inplace,
        within_intervals=within_intervals,
    )

IntervalSeriesSlicer

Bases: object

Source code in nelpy/core/_valeventarray.py
 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
class IntervalSeriesSlicer(object):
    def __init__(self):
        pass

    def __getitem__(self, *args):
        """intervals (e.g. epochs), series (e.g. units)"""
        # by default, keep all series
        seriesslice = slice(None, None, None)
        if isinstance(*args, int):
            intervalslice = args[0]
        elif isinstance(*args, core.IntervalArray):
            intervalslice = args[0]
        else:
            try:
                slices = np.s_[args]
                slices = slices[0]
                if len(slices) > 2:
                    raise IndexError(
                        "only [intervals, series] slicing is supported at this time!"
                    )
                elif len(slices) == 2:
                    intervalslice, seriesslice = slices
                else:
                    intervalslice = slices[0]
            except TypeError:
                # only interval to slice:
                intervalslice = slices

        return intervalslice, seriesslice

ItemGetter_iloc

Bases: object

.iloc is primarily integer position based (from 0 to length-1 of the axis).

.iloc will raise IndexError if a requested indexer is out-of-bounds, except slice indexers which allow out-of-bounds indexing. (this conforms with python/numpy slice semantics).

Allowed inputs are: - An integer e.g. 5 - A list or array of integers [4, 3, 0] - A slice object with ints 1:7

Source code in nelpy/core/_valeventarray.py
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
class ItemGetter_iloc(object):
    """.iloc is primarily integer position based (from 0 to length-1
    of the axis).

    .iloc will raise IndexError if a requested indexer is
    out-of-bounds, except slice indexers which allow out-of-bounds
    indexing. (this conforms with python/numpy slice semantics).

    Allowed inputs are:
        - An integer e.g. 5
        - A list or array of integers [4, 3, 0]
        - A slice object with ints 1:7
    """

    def __init__(self, obj):
        self.obj = obj

    def __getitem__(self, idx):
        """intervals, series"""
        intervalslice, seriesslice = IntervalSeriesSlicer()[idx]
        out = copy.copy(self.obj)
        if isinstance(seriesslice, int):
            seriesslice = [seriesslice]
        out._data = out._data[[seriesslice]]
        singleseries = len(out._data) == 1
        if singleseries:
            out._data = np.array(out._data[[0]], ndmin=2)
        out._series_ids = list(
            np.atleast_1d(np.atleast_1d(out._series_ids)[seriesslice])
        )

        # TODO: update tags
        if isinstance(intervalslice, slice):
            if (
                intervalslice.start is None
                and intervalslice.stop is None
                and intervalslice.step is None
            ):
                out.loc = ItemGetter_loc(out)
                out.iloc = ItemGetter_iloc(out)
                return out
        out = out._intervalslicer(intervalslice)
        out.loc = ItemGetter_loc(out)
        out.iloc = ItemGetter_iloc(out)
        return out

ItemGetter_loc

Bases: object

.loc is primarily label based (that is, series_id based)

.loc will raise KeyError when the items are not found.

Allowed inputs are: - A single label, e.g. 5 or 'a', (note that 5 is interpreted as a label of the index. This use is not an integer position along the index) - A list or array of labels ['a', 'b', 'c'] - A slice object with labels 'a':'f', (note that contrary to usual python slices, both the start and the stop are included!)

Source code in nelpy/core/_valeventarray.py
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
class ItemGetter_loc(object):
    """.loc is primarily label based (that is, series_id based)

    .loc will raise KeyError when the items are not found.

    Allowed inputs are:
        - A single label, e.g. 5 or 'a', (note that 5 is interpreted
            as a label of the index. This use is not an integer
            position along the index)
        - A list or array of labels ['a', 'b', 'c']
        - A slice object with labels 'a':'f', (note that contrary to
            usual python slices, both the start and the stop are
            included!)
    """

    def __init__(self, obj):
        self.obj = obj

    def __getitem__(self, idx):
        """intervals, series"""
        intervalslice, seriesslice = IntervalSeriesSlicer()[idx]

        # first convert series slice into list
        if isinstance(seriesslice, slice):
            start = seriesslice.start
            stop = seriesslice.stop
            istep = seriesslice.step
            try:
                if start is None:
                    istart = 0
                else:
                    istart = self.obj._series_ids.index(start)
            except ValueError:
                raise KeyError(
                    "series_id {} could not be found in BaseEventArray!".format(start)
                )
            try:
                if stop is None:
                    istop = self.obj.n_series
                else:
                    istop = self.obj._series_ids.index(stop) + 1
            except ValueError:
                raise KeyError(
                    "series_id {} could not be found in BaseEventArray!".format(stop)
                )
            if istep is None:
                istep = 1
            if istep < 0:
                istop -= 1
                istart -= 1
                istart, istop = istop, istart
            series_idx_list = list(range(istart, istop, istep))
        else:
            series_idx_list = []
            seriesslice = np.atleast_1d(seriesslice)
            for series in seriesslice:
                try:
                    uidx = self.obj.series_ids.index(series)
                except ValueError:
                    raise KeyError(
                        "series_id {} could not be found in BaseEventArray!".format(
                            series
                        )
                    )
                else:
                    series_idx_list.append(uidx)

        if not isinstance(series_idx_list, list):
            series_idx_list = list(series_idx_list)

        out = copy.copy(self.obj)
        try:
            out._data = out._data[[series_idx_list]]
            singleseries = len(out._data) == 1
        except AttributeError:
            out._data = out._data[[series_idx_list]]
            singleseries = len(out._data) == 1

        if singleseries:
            out._data = np.array([out._data[0]], ndmin=2)
        out._series_ids = list(
            np.atleast_1d(np.atleast_1d(out._series_ids)[[series_idx_list]])
        )
        # TODO: update tags
        if isinstance(intervalslice, slice):
            if (
                intervalslice.start is None
                and intervalslice.stop is None
                and intervalslice.step is None
            ):
                out.loc = ItemGetter_loc(out)
                out.iloc = ItemGetter_iloc(out)
                return out
        out = out._intervalslicer(intervalslice)
        out.loc = ItemGetter_loc(out)
        out.iloc = ItemGetter_iloc(out)
        return out

MarkedSpikeTrainArray

Bases: ValueEventArray

MarkedSpikeTrainArray for storing spike times with associated marks (e.g., waveform features).

This class extends ValueEventArray to support marks for each spike event, such as tetrode features or other metadata.

Parameters:

Name Type Description Default
events array - like

Spike times or event times.

required
marks array - like

Associated marks/features for each event.

required
support IntervalArray

Support intervals for the spike train.

required
fs float

Sampling frequency in Hz.

required
series_label str

Label for the series (e.g., 'tetrodes').

required
**kwargs

Additional keyword arguments passed to the parent class.

{}

Attributes:

Name Type Description
events array - like

Spike times or event times.

marks array - like

Associated marks/features for each event.

support IntervalArray

Support intervals for the spike train.

fs float

Sampling frequency in Hz.

series_label str

Label for the series.

Examples:

>>> msta = MarkedSpikeTrainArray(events=spike_times, marks=features, fs=30000)
>>> msta.events
array([...])
>>> msta.marks
array([...])
Source code in nelpy/core/_valeventarray.py
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
class MarkedSpikeTrainArray(ValueEventArray):
    """
    MarkedSpikeTrainArray for storing spike times with associated marks (e.g., waveform features).

    This class extends ValueEventArray to support marks for each spike event, such as tetrode features or other metadata.

    Parameters
    ----------
    events : array-like
        Spike times or event times.
    marks : array-like
        Associated marks/features for each event.
    support : nelpy.IntervalArray, optional
        Support intervals for the spike train.
    fs : float, optional
        Sampling frequency in Hz.
    series_label : str, optional
        Label for the series (e.g., 'tetrodes').
    **kwargs :
        Additional keyword arguments passed to the parent class.

    Attributes
    ----------
    events : array-like
        Spike times or event times.
    marks : array-like
        Associated marks/features for each event.
    support : nelpy.IntervalArray
        Support intervals for the spike train.
    fs : float
        Sampling frequency in Hz.
    series_label : str
        Label for the series.

    Examples
    --------
    >>> msta = MarkedSpikeTrainArray(events=spike_times, marks=features, fs=30000)
    >>> msta.events
    array([...])
    >>> msta.marks
    array([...])
    """

    # 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",
        "n_marks": "n_values",
        "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",
        "marks": "values",
        "spikes": "events",
    }

    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 = "tetrodes"
        kwargs["series_label"] = series_label

        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."""
        raise NotImplementedError
        return BinnedMarkedSpikeTrainArray(self, ds=ds)  # noqa: F821

bin(*, ds=None)

Return a BinnedSpikeTrainArray.

Source code in nelpy/core/_valeventarray.py
1335
1336
1337
1338
def bin(self, *, ds=None):
    """Return a BinnedSpikeTrainArray."""
    raise NotImplementedError
    return BinnedMarkedSpikeTrainArray(self, ds=ds)  # noqa: F821

StatefulValueEventArray

Bases: BaseValueEventArray

StatefulValueEventArray for storing events with associated values and states.

Parameters:

Name Type Description Default
events array - like

Event times for each series. List of arrays, shape (n_series, n_events_i).

None
values array - like

Values associated with each event. List of arrays, shape (n_series, n_events_i).

None
states array - like

States associated with each event. List of arrays, shape (n_series, n_events_i).

None
support IntervalArray

Support intervals for the events. If None, inferred from events.

None
fs float

Sampling frequency in Hz. Default is 30000.

None
series_ids list

List of series IDs. If None, defaults to [1, ..., n_series].

None
empty bool

If True, create an empty object.

False
**kwargs

Additional keyword arguments passed to the parent class.

{}

Attributes:

Name Type Description
events ndarray

Event times for each series. Ragged array, shape (n_series, n_events_i).

values ndarray

Values for each event. Ragged array, shape (n_series, n_events_i).

states ndarray

States for each event. Ragged array, shape (n_series, n_events_i).

support IntervalArray

Support intervals for the events.

fs float

Sampling frequency in Hz.

n_series int

Number of series.

n_events ndarray

Number of events in each series.

series_ids list

List of series IDs.

Examples:

>>> events = [[0.1, 0.5, 1.0], [0.2, 0.6, 1.2]]
>>> values = [[1, 2, 3], [4, 5, 6]]
>>> states = [[10, 20, 30], [40, 50, 60]]
>>> sveva = nel.StatefulValueEventArray(
...     events=events, values=values, states=states, fs=10
... )
>>> sveva.n_series
2
>>> sveva.n_events
array([3, 3])
>>> sveva.events[0]
array([0.1, 0.5, 1.0])
>>> sveva.values[0]
array([1, 2, 3])
>>> sveva.states[0]
array([10, 20, 30])
Source code in nelpy/core/_valeventarray.py
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
2195
2196
2197
class StatefulValueEventArray(BaseValueEventArray):
    """
    StatefulValueEventArray for storing events with associated values and states.

    Parameters
    ----------
    events : array-like
        Event times for each series. List of arrays, shape (n_series, n_events_i).
    values : array-like
        Values associated with each event. List of arrays, shape (n_series, n_events_i).
    states : array-like
        States associated with each event. List of arrays, shape (n_series, n_events_i).
    support : nelpy.IntervalArray, optional
        Support intervals for the events. If None, inferred from events.
    fs : float, optional
        Sampling frequency in Hz. Default is 30000.
    series_ids : list, optional
        List of series IDs. If None, defaults to [1, ..., n_series].
    empty : bool, optional
        If True, create an empty object.
    **kwargs
        Additional keyword arguments passed to the parent class.

    Attributes
    ----------
    events : np.ndarray
        Event times for each series. Ragged array, shape (n_series, n_events_i).
    values : np.ndarray
        Values for each event. Ragged array, shape (n_series, n_events_i).
    states : np.ndarray
        States for each event. Ragged array, shape (n_series, n_events_i).
    support : nelpy.IntervalArray
        Support intervals for the events.
    fs : float
        Sampling frequency in Hz.
    n_series : int
        Number of series.
    n_events : np.ndarray
        Number of events in each series.
    series_ids : list
        List of series IDs.

    Examples
    --------
    >>> events = [[0.1, 0.5, 1.0], [0.2, 0.6, 1.2]]
    >>> values = [[1, 2, 3], [4, 5, 6]]
    >>> states = [[10, 20, 30], [40, 50, 60]]
    >>> sveva = nel.StatefulValueEventArray(
    ...     events=events, values=values, states=states, fs=10
    ... )
    >>> sveva.n_series
    2
    >>> sveva.n_events
    array([3, 3])
    >>> sveva.events[0]
    array([0.1, 0.5, 1.0])
    >>> sveva.values[0]
    array([1, 2, 3])
    >>> sveva.states[0]
    array([10, 20, 30])
    """

    # 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",
        "n_marks": "n_values",
        "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",
        "marks": "values",
        "spikes": "events",
    }

    def __init__(
        self,
        events=None,
        values=None,
        states=None,
        *,
        fs=None,
        support=None,
        series_ids=None,
        empty=False,
        **kwargs,
    ):
        # add class-specific aliases to existing aliases:
        # self.__aliases__ = {**super().__aliases__, **self.__aliases__}
        # print('in init')
        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

        # print('non-stateful preprocessing')
        self._val_init(
            events=events,
            values=values,
            states=states,
            fs=fs,
            support=support,
            series_ids=series_ids,
            empty=empty,
            **kwargs,
        )

        # print('making stateful')
        data = self._make_stateful(data=self.data)
        self._data = data

    def _val_init(
        self,
        events=None,
        values=None,
        states=None,
        *,
        fs=None,
        support=None,
        series_ids=None,
        empty=False,
        **kwargs,
    ):
        #############################################
        #            standardize kwargs             #
        #############################################
        if events is not None:
            kwargs["events"] = events
        if values is not None:
            kwargs["values"] = values
        if states is not None:
            kwargs["states"] = states
        kwargs = self._standardize_kwargs(**kwargs)
        events = kwargs.pop("events", None)
        values = kwargs.pop("values", None)
        states = kwargs.pop("states", None)
        #############################################

        # 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.info(
                "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)
            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):
            # Handle ragged input: list/tuple or np.ndarray of dtype=object
            is_ragged = False
            if isinstance(data, (list, tuple)):
                try:
                    lengths = [len(np.atleast_1d(x)) for x in data]
                    if len(set(lengths)) > 1:
                        is_ragged = True
                except Exception:
                    pass
            elif isinstance(data, np.ndarray) and data.dtype == object:
                try:
                    lengths = [len(np.atleast_1d(x)) for x in data]
                    if len(set(lengths)) > 1:
                        is_ragged = True
                except Exception:
                    pass
            if is_ragged:
                return utils.ragged_array([np.array(st, ndmin=1) for st in data])
            # Only here, if not ragged, use np.array/np.squeeze
            return np.array(np.squeeze(data), ndmin=2)

        def standardize_values_to_2d(data):
            data = standardize_to_2d(data)
            for ii, series in enumerate(data):
                if len(series.shape) == 2:
                    pass
                else:
                    for xx in series:
                        if len(np.atleast_1d(xx)) > 1:
                            raise ValueError(
                                "each series must have a fixed number of values; mismatch in series {}".format(
                                    ii
                                )
                            )
            return data

        events = standardize_to_2d(events)
        values = standardize_values_to_2d(values)
        states = standardize_to_2d(states)

        data = []
        for a, v, s in zip(events, values, states):
            data.append(np.vstack((a, v.T, s.T)).T)
        data = np.array(data)

        # sort event series, but only if necessary:
        for ii, train in enumerate(events):
            if not utils.is_sorted(train):
                sortidx = np.argsort(train)
                data[ii] = (data[ii])[sortidx, :]

        kwargs["fs"] = fs
        kwargs["series_ids"] = series_ids

        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)

        # 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:
            self._abscissa.support = type(self._abscissa.support)(
                np.array([self.first_event, self.last_event + 1 / fs])
            )
        else:
            # restrict events to only those within the eventseries
            # array's support:
            self._abscissa.support = support

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

        self._data = data
        return

    @property
    def data(self):
        """Event datas in seconds."""
        return self._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 __iter__(self):
        """EventArray iterator initialization."""
        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 ValueEventArray.loc
        """
        return self.loc[idx]

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

    @support.setter
    def support(self, val):
        """(nelpy.IntervalArray) The support of the underlying 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._data = self._restrict_to_interval_array_value_fast(
            intervalarray=self._abscissa.support, data=self.data, copyover=True
        )

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

    @domain.setter
    def domain(self, val):
        """(nelpy.IntervalArray) The domain of the underlying 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._data = self._restrict_to_interval_array_value_fast(
            intervalarray=self._abscissa.support, data=self.data, copyover=True
        )

    def _intervalslicer(self, idx):
        """Helper function to restrict object to EpochArray."""
        # if self.isempty:
        #     return self

        if isinstance(idx, core.IntervalArray):
            if idx.isempty:
                return type(self)(empty=True)
            support = self._abscissa.support.intersect(
                interval=idx, boundaries=True
            )  # what if fs of slicing interval is different?
            if support.isempty:
                return type(self)(empty=True)

            logging.disable(logging.CRITICAL)
            data = self._restrict_to_interval_array_value_fast(
                intervalarray=support, data=self.data, copyover=True
            )
            eventarray = self._copy_without_data()
            eventarray._data = data
            eventarray._abscissa.support = support
            eventarray.__renew__()
            logging.disable(0)
            return eventarray
        elif isinstance(idx, int):
            eventarray = self._copy_without_data()
            support = self._abscissa.support[idx]
            eventarray._abscissa.support = support
            if (idx >= self._abscissa.support.n_intervals) or idx < (
                -self._abscissa.support.n_intervals
            ):
                eventarray.__renew__()
                return eventarray
            else:
                data = self._restrict_to_interval_array_value_fast(
                    intervalarray=support, data=self.data, copyover=True
                )
                eventarray._data = data
                eventarray._abscissa.support = support
                eventarray.__renew__()
                return eventarray
        else:  # most likely slice indexing
            try:
                logging.disable(logging.CRITICAL)
                support = self._abscissa.support[idx]
                data = self._restrict_to_interval_array_value_fast(
                    intervalarray=support, data=self.data, copyover=True
                )
                eventarray = self._copy_without_data()
                eventarray._data = data
                eventarray._abscissa.support = support
                eventarray.__renew__()
                logging.disable(0)
                return eventarray
            except Exception:
                raise TypeError("unsupported subsctipting type {}".format(type(idx)))

    @staticmethod
    def _restrict_to_interval_array_fast(intervalarray, data, copyover=True):
        """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 : IntervalArray or EpochArray
        data : list or array-like, each element of size (n_events, n_values).
        """
        if intervalarray.isempty:
            n_series = len(data)
            data = np.zeros((n_series, 0))
            return data

        singleseries = len(data) == 1  # bool

        # TODO: is this copy even necessary?
        if copyover:
            data = copy.copy(data)

        # NOTE: this used to assume multiple series for the enumeration to work
        for series, evt_data in enumerate(data):
            indices = []
            for epdata in intervalarray.data:
                t_start = epdata[0]
                t_stop = epdata[1]
                frm, to = np.searchsorted(evt_data[:, 0], (t_start, t_stop))
                indices.append((frm, to))
            indices = np.array(indices, ndmin=2)
            if np.diff(indices).sum() < len(evt_data):
                logging.info("ignoring events outside of eventarray support")
            if singleseries:
                data_list = []
                for start, stop in indices:
                    data_list.extend(evt_data[start:stop])
                data = np.array([data_list])
            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()
                data_[series] = np.array(data_list)
                data = utils.ragged_array(data_)
        return data

    def _restrict_to_interval_array_value_fast(
        self, intervalarray, data, copyover=True
    ):
        """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 : IntervalArray or EpochArray
        data : list or array-like, each element of size (n_events, n_values).
        """
        if intervalarray.isempty:
            n_series = len(data)
            data = np.zeros((n_series, 0))
            return data

        # plan of action
        # create pseudo events supporting each interval
        # then restrict existing data (pseudo and real events)
        # then merge in all pseudo events that don't exist yet
        starts = intervalarray.starts
        stops = intervalarray.stops

        kinds = []
        events = []
        states = []

        for series in data:
            tvect = series[:, 0].astype(float)
            statevals = series[:, 2:]

            kind = []
            state = []

            for start in starts:
                idx = np.max((np.searchsorted(tvect, start, side="right") - 1, 0))
                kind.append(0)
                state.append(statevals[[idx]])

            for stop in stops:
                idx = np.max((np.searchsorted(tvect, stop, side="right") - 1, 0))
                kind.append(2)
                state.append(statevals[[idx]])

            states.append(np.array(state).squeeze())  ## squeeze???
            events.append(np.hstack((starts, stops)))
            kinds.append(np.array(kind))

        pseudodata = []
        for e, k, s in zip(events, kinds, states):
            pseudodata.append(np.vstack((e, k, s.T)).T)

        pseudodata = utils.ragged_array(pseudodata)

        singleseries = len(data) == 1  # bool

        # TODO: is this copy even necessary?
        if copyover:
            data = copy.copy(data)

        # NOTE: this used to assume multiple series for the enumeration to work
        for series, evt_data in enumerate(data):
            indices = []
            for epdata in intervalarray.data:
                t_start = epdata[0]
                t_stop = epdata[1]
                frm, to = np.searchsorted(evt_data[:, 0], (t_start, t_stop))
                indices.append((frm, to))
            indices = np.array(indices, ndmin=2)
            if np.diff(indices).sum() < len(evt_data):
                logging.info("ignoring events outside of eventarray support")
            if singleseries:
                data_list = []
                for start, stop in indices:
                    data_list.extend(evt_data[start:stop])
                data = np.array([data_list])
            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()
                data_[series] = np.array(data_list)
                data = utils.ragged_array(data_)

        # now add in all pseudo events that don't already exist in data

        kinds = []
        events = []
        states = []

        for pseries, series in zip(pseudodata, data):
            ptvect = pseries[:, 0].astype(float)
            pkind = pseries[:, 1].astype(int)
            pstatevals = pseries[:, 2:]

            try:
                tvect = series[:, 0].astype(float)
                kind = series[:, 1]
                statevals = series[:, 2:]
            except IndexError:
                tvect = np.zeros((0))
                kind = np.zeros((0))
                statevals = np.zeros((0,))

            for tt, kk, psv in zip(ptvect, pkind, pstatevals):
                # print(tt, kk, psv)
                idx = np.searchsorted(tvect, tt, side="right")
                idx2 = np.max((idx - 1, 0))
                try:
                    if tt == tvect[idx2]:
                        pass
                        # print('pseudo event {} not necessary...'.format(tt))
                    else:
                        # print('pseudo event {} necessary...'.format(tt))
                        kind = np.insert(kind, idx, kk)
                        tvect = np.insert(tvect, idx, tt)
                        statevals = np.insert(statevals, idx, psv, axis=0)
                except IndexError:
                    kind = np.insert(kind, idx, kk)
                    tvect = np.insert(tvect, idx, tt)
                    statevals = np.insert(statevals, idx, psv, axis=0)

            states.append(np.array(statevals).squeeze())
            events.append(tvect)
            kinds.append(kind)

        # print(states)
        # print(tvect)
        # print(kinds)

        data = []
        for e, k, s in zip(events, kinds, states):
            data.append(np.vstack((e, k, s.T)).T)

        data = utils.ragged_array(data)

        return data

    def bin(self, *, ds=None):
        """Return a BinnedValueEventArray."""
        raise NotImplementedError
        return BinnedValueEventArray(self, ds=ds)

    def __call__(self, *args):
        """StatefulValueEventArray callable method; by default returns state values"""
        values = []
        for events, vals in zip(self.state_events, self.state_values):
            idx = np.searchsorted(events, args, side="right") - 1
            idx[idx < 0] = 0
            values.append(vals[[idx]])
        values = np.asarray(values)
        return values

    def _make_stateful(self, data, intervalarray=None, initial_state=np.nan):
        """
        [i, e0, e1, e2, ..., f] for every epoch

        matrix of size (n_values x (n_epochs*2 + n_events) )
        matrix of size (nSeries: n_values x (n_epochs*2 + n_events) )

        needs to change when calling loc, iloc, restrict, getitem, ...

        TODO: initial_state is not used yet!!!
        """
        kinds = []
        events = []
        states = []

        if intervalarray is None:
            intervalarray = self.support

        for series in data:
            starts = intervalarray.starts
            stops = intervalarray.stops
            tvect = series[:, 0].astype(float)
            statevals = series[:, 1:]
            kind = np.ones(tvect.size).astype(int)

            for start in starts:
                idx = np.searchsorted(tvect, start, side="right")
                idx2 = np.max((idx - 1, 0))
                if start == tvect[idx2]:
                    continue
                else:
                    kind = np.insert(kind, idx, 0)
                    tvect = np.insert(tvect, idx, start)
                    statevals = np.insert(statevals, idx, statevals[idx2], axis=0)

            for stop in stops:
                idx = np.searchsorted(tvect, stop, side="right")
                idx2 = np.max((idx - 1, 0))
                if stop == tvect[idx2]:
                    continue
                else:
                    kind = np.insert(kind, idx, 2)
                    tvect = np.insert(tvect, idx, stop)
                    statevals = np.insert(statevals, idx, statevals[idx2], axis=0)

            states.append(statevals)
            events.append(tvect)
            kinds.append(kind)

        data = []
        for e, k, s in zip(events, kinds, states):
            data.append(np.vstack((e, k, s.T)).T)
        data = utils.ragged_array(data)

        return data

    @property
    def n_values(self):
        """(int) The number of values associated with each event series."""
        if self.isempty:
            return 0
        n_values = []
        for series in self.data:
            n_values.append(series.squeeze().shape[1] - 2)
        return n_values

    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 = ""
        numstr = " %s %s" % (self.n_series, self._series_label)
        logging.disable(0)
        return "<%s%s:%s%s>%s" % (self.type_name, address_str, numstr, epstr, fsstr)

    @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.events])

    @property
    def events(self):
        events = []
        for series, kinds in zip(self.state_events, self.state_kinds):
            keep_idx = np.argwhere(kinds == 1)
            events.append(series[keep_idx].squeeze())
        return np.asarray(events)

    @property
    def values(self):
        values = []
        for series, kinds in zip(self.state_values, self.state_kinds):
            keep_idx = np.argwhere(kinds == 1)
            values.append(series[keep_idx].squeeze())
        return np.asarray(values)

    @property
    def state_events(self):
        events = []
        for series in self.data:
            events.append(series[:, 0].squeeze())

        return np.asarray(events)

    @property
    def state_values(self):
        values = []
        for series in self.data:
            values.append(series[:, 2:].squeeze())

        return np.asarray(values)

    @property
    def state_kinds(self):
        values = []
        for series in self.data:
            values.append(series[:, 1].squeeze())

        return np.asarray(values)

    def _plot(self, *args, **kwargs):
        if self.n_series > 1:
            raise NotImplementedError
        if np.any(np.array(self.n_values) > 1):
            raise NotImplementedError

        import matplotlib.pyplot as plt

        events = self.state_events.squeeze()
        values = self.state_values.squeeze()
        kinds = self.state_kinds.squeeze()

        for (a, b), val, (ka, kb) in zip(
            utils.pairwise(events), values, utils.pairwise(kinds)
        ):
            if kb == 1:
                plt.plot(
                    [a, b],
                    [val, val],
                    "-",
                    color="b",
                    markerfacecolor="w",
                    lw=1.5,
                    mew=1.5,
                )
            if ka == 1:
                plt.plot(
                    [a, b],
                    [val, val],
                    "-",
                    color="g",
                    markerfacecolor="w",
                    lw=1.5,
                    mew=1.5,
                )
            if kb == 1:
                plt.plot(b, val, "o", color="k", markerfacecolor="w", lw=1.5, mew=1.5)
            if ka == 1:
                plt.plot(a, val, "o", color="k", markerfacecolor="k", lw=1.5, mew=1.5)
            if ka == 0 and kb == 2:
                plt.plot(
                    [a, b],
                    [val, val],
                    "-",
                    color="r",
                    markerfacecolor="w",
                    lw=1.5,
                    mew=1.5,
                )

data property

Event datas in seconds.

domain property writable

(nelpy.IntervalArray) The domain of the underlying EventArray.

n_events property

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

n_values property

(int) The number of values associated with each event series.

support property writable

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

bin(*, ds=None)

Return a BinnedValueEventArray.

Source code in nelpy/core/_valeventarray.py
2004
2005
2006
2007
def bin(self, *, ds=None):
    """Return a BinnedValueEventArray."""
    raise NotImplementedError
    return BinnedValueEventArray(self, ds=ds)

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/_valeventarray.py
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
@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

ValueEventArray

Bases: BaseValueEventArray

A multiseries eventarray with shared support.

Parameters:

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

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

required
fs float

Sampling rate in Hz. Default is 30,000

None
support EpochArray

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

None
label str or None

Information pertaining to the source of the eventarray.

required
cell_type list (of length n_series) of str or other

Identified cell type indicator, e.g., 'pyr', 'int'.

required
series_ids list (of length n_series) of indices corresponding to

curated data. If no series_ids are specified, then [1,...,n_series] will be used. WARNING! The first series will have index 1, not 0!

None
meta dict

Metadata associated with eventarray.

required

Attributes:

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

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

support EpochArray on which eventarray is defined.
n_events np.array(dtype=np.int) of shape (n_series,)

Number of events in each series.

fs float

Sampling frequency (Hz).

cell_types np.array of str or other

Identified cell type for each series.

label str or None

Information pertaining to the source of the eventarray.

meta dict

Metadata associated with eventseries.

Source code in nelpy/core/_valeventarray.py
 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
1029
1030
1031
1032
1033
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
class ValueEventArray(BaseValueEventArray):
    """A multiseries eventarray with shared support.

    Parameters
    ----------
    data : 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 : EpochArray, optional
        EpochArray on which eventarrays are defined.
        Default is [0, last event] inclusive.
    label : str or None, optional
        Information pertaining to the source of the eventarray.
    cell_type : list (of length n_series) of str or other, optional
        Identified cell type indicator, e.g., 'pyr', 'int'.
    series_ids : list (of length n_series) of indices corresponding to
        curated data. If no series_ids are specified, then [1,...,n_series]
        will be used. WARNING! The first series will have index 1, not 0!
    meta : dict
        Metadata associated with eventarray.

    Attributes
    ----------
    data : array of np.array(dtype=np.float64) event datas in seconds.
        Array of length n_series, each entry with shape (n_data,)
    support : EpochArray on which eventarray is defined.
    n_events: np.array(dtype=np.int) of shape (n_series,)
        Number of events in each series.
    fs: float
        Sampling frequency (Hz).
    cell_types : np.array of str or other
        Identified cell type for each series.
    label : str or None
        Information pertaining to the source of the eventarray.
    meta : dict
        Metadata associated with eventseries.
    """

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

    def __init__(
        self,
        events=None,
        values=None,
        *,
        fs=None,
        support=None,
        series_ids=None,
        empty=False,
        **kwargs,
    ):
        self._val_init(
            events=events,
            values=values,
            fs=fs,
            support=support,
            series_ids=series_ids,
            empty=empty,
            **kwargs,
        )

    def _val_init(
        self,
        events=None,
        values=None,
        *,
        fs=None,
        support=None,
        series_ids=None,
        empty=False,
        **kwargs,
    ):
        #############################################
        #            standardize kwargs             #
        #############################################
        if events is not None:
            kwargs["events"] = events
        if values is not None:
            kwargs["values"] = values
        kwargs = self._standardize_kwargs(**kwargs)
        events = kwargs.pop("events", None)
        values = kwargs.pop("values", None)
        #############################################

        # 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.info(
                "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)."""
            # Avoid np.array on jagged input
            if isinstance(data, (list, tuple)) and len(data) > 1:
                # If all elements are scalars or 1-element lists/arrays
                try:
                    if all(
                        (not hasattr(x, "__len__") or len(np.atleast_1d(x)) == 1)
                        for x in data
                    ):
                        return True
                except Exception:
                    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
            """
            # Avoid np.array on jagged input
            try:
                # If first element is a list/array and has more than 1 element, not single series
                if hasattr(data[0], "__len__") and len(data[0]) > 1:
                    # If data[0][0] is also a list/array, too many layers
                    if hasattr(data[0][0], "__len__"):
                        return False
                # If second element exists and is a list/array, not single series
                if len(data) > 1 and hasattr(data[1], "__len__"):
                    return False
            except Exception:
                pass
            return True

        def standardize_to_2d(data):
            # Handle ragged input: list/tuple or np.ndarray of dtype=object
            is_ragged = False
            if isinstance(data, (list, tuple)):
                try:
                    lengths = [len(np.atleast_1d(x)) for x in data]
                    if len(set(lengths)) > 1:
                        is_ragged = True
                except Exception:
                    pass
            elif isinstance(data, np.ndarray) and data.dtype == object:
                try:
                    lengths = [len(np.atleast_1d(x)) for x in data]
                    if len(set(lengths)) > 1:
                        is_ragged = True
                except Exception:
                    pass
            if is_ragged:
                return utils.ragged_array([np.array(st, ndmin=1) for st in data])
            # Only here, if not ragged, use np.array/np.squeeze
            return np.array(np.squeeze(data), ndmin=2)

        def standardize_values_to_2d(data):
            data = standardize_to_2d(data)
            for ii, series in enumerate(data):
                if len(series.shape) == 2:
                    pass
                else:
                    for xx in series:
                        if len(np.atleast_1d(xx)) > 1:
                            raise ValueError(
                                "each series must have a fixed number of values; mismatch in series {}".format(
                                    ii
                                )
                            )
            return data

        events = standardize_to_2d(events)
        values = standardize_values_to_2d(values)

        data = []
        for a, v in zip(events, values):
            data.append(np.vstack((a, v.T)).T)
        # Use ragged_array to support jagged arrays (multi-series with different numbers of events)
        data = utils.ragged_array(data)

        # sort event series, but only if necessary:
        for ii, train in enumerate(events):
            if not utils.is_sorted(train):
                sortidx = np.argsort(train)
                data[ii] = (data[ii])[sortidx, :]

        kwargs["fs"] = fs
        kwargs["series_ids"] = series_ids

        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:
            self.support = type(self._abscissa.support)(
                np.array([self.first_event, self.last_event + 1 / fs])
            )
        else:
            # restrict events to only those within the eventseries
            # array's support:
            # print('restricting, here')
            self.support = support

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

        self._data = data
        return

    @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 __iter__(self):
        """EventArray iterator initialization."""
        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 _intervalslicer(self, idx):
        """Helper function to restrict object to EpochArray."""
        # if self.isempty:
        #     return self

        if isinstance(idx, core.IntervalArray):
            if idx.isempty:
                return type(self)(empty=True)
            support = self._abscissa.support.intersect(
                interval=idx, boundaries=True
            )  # what if fs of slicing interval is different?
            if support.isempty:
                return type(self)(empty=True)

            logging.disable(logging.CRITICAL)
            data = self._restrict_to_interval_array_fast(
                intervalarray=support, data=self.data, copyover=True
            )
            eventarray = self._copy_without_data()
            eventarray._data = data
            eventarray._abscissa.support = support
            eventarray.__renew__()
            logging.disable(0)
            return eventarray
        elif isinstance(idx, int):
            eventarray = self._copy_without_data()
            support = self._abscissa.support[idx]
            eventarray._abscissa.support = support
            if (idx >= self._abscissa.support.n_intervals) or idx < (
                -self._abscissa.support.n_intervals
            ):
                eventarray.__renew__()
                return eventarray
            else:
                data = self._restrict_to_interval_array_fast(
                    intervalarray=support, data=self.data, copyover=True
                )
                eventarray._data = data
                eventarray._abscissa.support = support
                eventarray.__renew__()
                return eventarray
        else:  # most likely slice indexing
            try:
                logging.disable(logging.CRITICAL)
                support = self._abscissa.support[idx]
                data = self._restrict_to_interval_array_fast(
                    intervalarray=support, data=self.data, copyover=True
                )
                eventarray = self._copy_without_data()
                eventarray._data = data
                eventarray._abscissa.support = support
                eventarray.__renew__()
                logging.disable(0)
                return eventarray
            except Exception:
                raise TypeError("unsupported subsctipting type {}".format(type(idx)))

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

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

    @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))

    @property
    def events(self):
        events = []
        for series in self.data:
            events.append(series[:, 0].squeeze())
        return utils.ragged_array(events)

    @property
    def values(self):
        values = []
        for series in self.data:
            values.append(series[:, 1:].squeeze())
        return utils.ragged_array(values)

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

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

        # default args:
        if series_id is None:
            series_id = 0

        flattened = self._copy_without_data()

        flattened._series_ids = [series_id]

        raise NotImplementedError
        alldatas = self.data[0]
        for series in range(1, self.n_series):
            alldatas = utils.linear_merge(alldatas, self.data[series])

        flattened._data = np.array(list(alldatas), ndmin=2)
        flattened.__renew__()
        return flattened

    @staticmethod
    def _restrict_to_interval_array_fast(intervalarray, data, copyover=True):
        """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 : IntervalArray or EpochArray
        data : list or array-like, each element of size (n_events, n_values).
        """
        if intervalarray.isempty:
            n_series = len(data)
            data = np.zeros((n_series, 0))
            return data

        singleseries = len(data) == 1  # bool

        # TODO: is this copy even necessary?
        if copyover:
            data = copy.copy(data)

        # NOTE: this used to assume multiple series for the enumeration to work
        for series, evt_data in enumerate(data):
            evt_data = ValueEventArray._to_2d_array(evt_data)
            if evt_data.size == 0 or evt_data.shape[1] < 1:
                if singleseries:
                    data = np.array([[]])
                else:
                    data_ = data.tolist()
                    data_[series] = np.array([])
                    data = utils.ragged_array(data_)
                continue
            indices = []
            for epdata in intervalarray.data:
                t_start = epdata[0]
                t_stop = epdata[1]
                # Ensure we have a proper 1D array of event times
                if evt_data.ndim > 1:
                    event_times = evt_data[:, 0].flatten()
                else:
                    event_times = evt_data.flatten()
                # Ensure event_times is a proper 1D array and not an object array
                if event_times.dtype == object:
                    # Handle object array by extracting the actual values
                    event_times = np.array(
                        [
                            float(t) if hasattr(t, "__float__") else t
                            for t in event_times
                        ]
                    )
                # Ensure event_times is a proper 1D array
                if event_times.size == 0:
                    indices.append((0, 0))
                else:
                    try:
                        frm, to = np.searchsorted(event_times, (t_start, t_stop))
                        indices.append((frm, to))
                    except (ValueError, TypeError):
                        # Fallback: handle case where searchsorted fails
                        indices.append((0, 0))
            indices = np.array(indices, ndmin=2)
            if np.diff(indices).sum() < len(evt_data):
                logging.info("ignoring events outside of eventarray support")
            if singleseries:
                data_list = []
                for start, stop in indices:
                    data_list.extend(evt_data[start:stop])
                data = np.array([data_list])
            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()
                data_[series] = np.array(data_list)
                data = utils.ragged_array(data_)
        return data

    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 = ""
        numstr = " %s %s" % (self.n_series, self._series_label)
        logging.disable(0)
        return "<%s%s:%s%s>%s" % (self.type_name, address_str, numstr, epstr, fsstr)

    def bin(self, *, ds=None, method="mean", **kwargs):
        """Return a binned value event array.

        method in [sum, mean, median, min, max] or a custom function.
        Additional keyword arguments are passed to BinnedValueEventArray.
        """
        return BinnedValueEventArray(self, ds=ds, method=method, **kwargs)

    @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 n_values(self):
        """(int) The number of values associated with each event series."""
        if self.isempty:
            return 0
        n_values = []
        for series in self.data:
            n_values.append(series.squeeze().shape[1] - 1)
        return n_values

    @property
    def issorted(self):
        """(bool) Sorted EventArray."""
        if self.isempty:
            return True
        return np.array(
            [utils.is_sorted(eventarray[:, 0]) 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],
            )
            # 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_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],
            )
            # TODO: re-build series tags (tag system not yet implemented)
            oldorder[frm], oldorder[to] = oldorder[to], oldorder[frm]

        out.__renew__()
        return out

    def make_stateful(self):
        raise NotImplementedError

    @staticmethod
    def _to_2d_array(arr):
        """Convert array to 2D numpy array, handling object arrays properly."""
        if isinstance(arr, np.ndarray) and arr.dtype == object:
            # Handle object arrays by extracting the actual data
            if arr.size == 1:
                # Single element object array
                return np.atleast_2d(arr[0])
            else:
                # Multiple element object array - concatenate
                flattened = []
                for item in arr:
                    if isinstance(item, np.ndarray):
                        flattened.append(item)
                    else:
                        flattened.append(np.array(item))
                if flattened:
                    return np.vstack(flattened)
                else:
                    return np.array([]).reshape(0, 0)
        else:
            return np.atleast_2d(arr)

issorted property

(bool) Sorted EventArray.

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_values property

(int) The number of values associated with each event series.

bin(*, ds=None, method='mean', **kwargs)

Return a binned value event array.

method in [sum, mean, median, min, max] or a custom function. Additional keyword arguments are passed to BinnedValueEventArray.

Source code in nelpy/core/_valeventarray.py
1109
1110
1111
1112
1113
1114
1115
def bin(self, *, ds=None, method="mean", **kwargs):
    """Return a binned value event array.

    method in [sum, mean, median, min, max] or a custom function.
    Additional keyword arguments are passed to BinnedValueEventArray.
    """
    return BinnedValueEventArray(self, ds=ds, method=method, **kwargs)

flatten(*, series_id=None)

Collapse events across series.

Parameters:

Name Type Description Default
series_id

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

None
Source code in nelpy/core/_valeventarray.py
 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
def flatten(self, *, series_id=None):
    """Collapse events across series.

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

    # default args:
    if series_id is None:
        series_id = 0

    flattened = self._copy_without_data()

    flattened._series_ids = [series_id]

    raise NotImplementedError
    alldatas = self.data[0]
    for series in range(1, self.n_series):
        alldatas = utils.linear_merge(alldatas, self.data[series])

    flattened._data = np.array(list(alldatas), ndmin=2)
    flattened.__renew__()
    return flattened

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/_valeventarray.py
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
@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_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/_valeventarray.py
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
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],
        )
        # TODO: re-build series tags (tag system not yet implemented)
        oldorder[frm], oldorder[to] = oldorder[to], oldorder[frm]

    out.__renew__()
    return out