Skip to content

AnalogSignalArray

RegularlySampledAnalogSignalArray

Core object definition and implementation for RegularlySampledAnalogSignalArray.

AbscissaSlicer

Bases: object

Slicer for extracting abscissa values from analog signal arrays by interval.

Parameters:

Name Type Description Default
parent object

The parent object to slice.

required
Source code in nelpy/core/_analogsignalarray.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
class AbscissaSlicer(object):
    """
    Slicer for extracting abscissa values from analog signal arrays by interval.

    Parameters
    ----------
    parent : object
        The parent object to slice.
    """

    def __init__(self, parent):
        """
        Initialize the AbscissaSlicer.

        Parameters
        ----------
        parent : object
            The parent object to slice.
        """
        self._parent = parent

    def _abscissa_vals_generator(self, interval_indices):
        """
        Generator for abscissa values by interval.

        Parameters
        ----------
        interval_indices : list or array-like
            Indices of intervals.

        Yields
        ------
        abscissa_vals : np.ndarray
            Abscissa values for each interval.
        """
        for start, stop in interval_indices:
            try:
                yield self._parent._abscissa_vals[start:stop]
            except StopIteration:
                return

    def __getitem__(self, idx):
        intervalslice, signalslice = self._parent._intervalsignalslicer[idx]

        interval_indices = self._parent._data_interval_indices()
        interval_indices = np.atleast_2d(interval_indices[intervalslice])

        if len(interval_indices) < 2:
            start, stop = interval_indices[0]
            return self._parent._abscissa_vals[start:stop]
        else:
            return self._abscissa_vals_generator(interval_indices)

    def plot_generator(self):
        interval_indices = self._parent._data_interval_indices()
        for start, stop in interval_indices:
            try:
                yield self._parent._abscissa_vals[start:stop]
            except StopIteration:
                return

    def __iter__(self):
        self._index = 0
        return self

    def __next__(self):
        index = self._index

        if index > self._parent.n_intervals - 1:
            raise StopIteration

        interval_indices = self._parent._data_interval_indices()
        interval_indices = interval_indices[index]
        start, stop = interval_indices

        self._index += 1

        return self._parent._abscissa_vals[start:stop]

AnalogSignalArray

Bases: RegularlySampledAnalogSignalArray

Array of continuous analog signals with regular sampling rates.

This class extends RegularlySampledAnalogSignalArray with additional aliases and legacy support for backward compatibility.

Parameters:

Name Type Description Default
data ndarray

Array of signal data with shape (n_signals, n_samples). Default is empty array.

required
abscissa_vals ndarray

Time values corresponding to samples, with shape (n_samples,). Default is None.

required
fs float

Sampling frequency in Hz. Default is None.

required
step float

Sampling interval in seconds. Default is None.

required
merge_sample_gap float

Maximum gap between samples to merge intervals (seconds). Default is 0.

required
support IntervalArray

Time intervals where signal is defined. Default is None.

required
in_core bool

Whether to keep data in core memory. Default is True.

required
labels array - like

Labels for each signal. Default is None.

required
empty bool

If True, creates empty array. Default is False.

required
abscissa AnalogSignalArrayAbscissa

Abscissa object. Default is created from support.

required
ordinate AnalogSignalArrayOrdinate

Ordinate object. Default is empty.

required
Aliases

time : abscissa_vals Alias for time values.

n_epochs : n_intervals Alias for number of intervals. ydata : data Legacy alias for data.

Examples:

>>> import numpy as np
>>> from nelpy import AnalogSignalArray
>>> # Create a simple sine wave signal
>>> time = np.linspace(0, 1, 1000)  # 1 second of data
>>> signal = np.sin(2 * np.pi * 5 * time)  # 5 Hz sine wave
>>> # Create AnalogSignalArray with default parameters
>>> asa = AnalogSignalArray(
...     data=signal[np.newaxis, :], abscissa_vals=time, fs=1000
... )  # 1 kHz sampling
>>> # Access data using different aliases
>>> print(asa.data.shape)  # (1, 1000)
>>> print(asa.ydata.shape)  # same as data (legacy alias)
>>> print(asa.time.shape)  # (1000,) alias for abscissa_vals
>>> # Plot the signal (requires matplotlib)
>>> # asa.plot()
>>> # Create multi-channel signal with labels
>>> signals = np.vstack([signal, np.cos(2 * np.pi * 5 * time)])  # add cosine wave
>>> asa2 = AnalogSignalArray(
...     data=signals, abscissa_vals=time, fs=1000, labels=["sine", "cosine"]
... )
>>> # Access individual channels
>>> sine_channel = asa2[:, 0]
>>> cosine_channel = asa2[:, 1]
Notes
  • Inherits all attributes and methods from RegularlySampledAnalogSignalArray
  • Provides backward compatibility with legacy parameter names
  • Automatically handles abscissa and ordinate objects if not provided
See Also

RegularlySampledAnalogSignalArray : Parent class with core functionality

Source code in nelpy/core/_analogsignalarray.py
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
class AnalogSignalArray(RegularlySampledAnalogSignalArray):
    """Array of continuous analog signals with regular sampling rates.

    This class extends RegularlySampledAnalogSignalArray with additional aliases
    and legacy support for backward compatibility.

    Parameters
    ----------
    data : np.ndarray, optional
        Array of signal data with shape (n_signals, n_samples).
        Default is empty array.
    abscissa_vals : np.ndarray, optional
        Time values corresponding to samples, with shape (n_samples,).
        Default is None.
    fs : float, optional
        Sampling frequency in Hz. Default is None.
    step : float, optional
        Sampling interval in seconds. Default is None.
    merge_sample_gap : float, optional
        Maximum gap between samples to merge intervals (seconds).
        Default is 0.
    support : nelpy.IntervalArray, optional
        Time intervals where signal is defined. Default is None.
    in_core : bool, optional
        Whether to keep data in core memory. Default is True.
    labels : array-like, optional
        Labels for each signal. Default is None.
    empty : bool, optional
        If True, creates empty array. Default is False.
    abscissa : nelpy.core.AnalogSignalArrayAbscissa, optional
        Abscissa object. Default is created from support.
    ordinate : nelpy.core.AnalogSignalArrayOrdinate, optional
        Ordinate object. Default is empty.

    Aliases
    -------
    time : abscissa_vals
        Alias for time values.

    n_epochs : n_intervals
        Alias for number of intervals.
    ydata : data
        Legacy alias for data.

    Examples
    --------
    >>> import numpy as np
    >>> from nelpy import AnalogSignalArray

    >>> # Create a simple sine wave signal
    >>> time = np.linspace(0, 1, 1000)  # 1 second of data
    >>> signal = np.sin(2 * np.pi * 5 * time)  # 5 Hz sine wave

    >>> # Create AnalogSignalArray with default parameters
    >>> asa = AnalogSignalArray(
    ...     data=signal[np.newaxis, :], abscissa_vals=time, fs=1000
    ... )  # 1 kHz sampling

    >>> # Access data using different aliases
    >>> print(asa.data.shape)  # (1, 1000)
    >>> print(asa.ydata.shape)  # same as data (legacy alias)
    >>> print(asa.time.shape)  # (1000,) alias for abscissa_vals

    >>> # Plot the signal (requires matplotlib)
    >>> # asa.plot()

    >>> # Create multi-channel signal with labels
    >>> signals = np.vstack([signal, np.cos(2 * np.pi * 5 * time)])  # add cosine wave
    >>> asa2 = AnalogSignalArray(
    ...     data=signals, abscissa_vals=time, fs=1000, labels=["sine", "cosine"]
    ... )

    >>> # Access individual channels
    >>> sine_channel = asa2[:, 0]
    >>> cosine_channel = asa2[:, 1]

    Notes
    -----
    - Inherits all attributes and methods from RegularlySampledAnalogSignalArray
    - Provides backward compatibility with legacy parameter names
    - Automatically handles abscissa and ordinate objects if not provided

    See Also
    --------
    RegularlySampledAnalogSignalArray : Parent class with core functionality
    """

    # specify class-specific aliases:
    __aliases__ = {
        "time": "abscissa_vals",
        "_time": "_abscissa_vals",
        "n_epochs": "n_intervals",
        "ydata": "data",  # legacy support
        "_ydata": "_data",  # legacy support
    }

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

        # legacy ASA constructor support for backward compatibility
        kwargs = legacyASAkwargs(**kwargs)

        support = kwargs.get("support", core.EpochArray(empty=True))
        abscissa = kwargs.get(
            "abscissa", core.AnalogSignalArrayAbscissa(support=support)
        )
        ordinate = kwargs.get("ordinate", core.AnalogSignalArrayOrdinate())

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

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

DataSlicer

Bases: object

Slicer for extracting data from analog signal arrays by interval and signal.

Parameters:

Name Type Description Default
parent object

The parent object to slice.

required
Source code in nelpy/core/_analogsignalarray.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
class DataSlicer(object):
    """
    Slicer for extracting data from analog signal arrays by interval and signal.

    Parameters
    ----------
    parent : object
        The parent object to slice.
    """

    def __init__(self, parent):
        """
        Initialize the DataSlicer.

        Parameters
        ----------
        parent : object
            The parent object to slice.
        """
        self._parent = parent

    def _data_generator(self, interval_indices, signalslice):
        """
        Generator for data slices by interval and signal.

        Parameters
        ----------
        interval_indices : list or array-like
            Indices of intervals.
        signalslice : int or slice
            Signal slice.

        Yields
        ------
        data : np.ndarray
            Data for each interval and signal.
        """
        for start, stop in interval_indices:
            try:
                yield self._parent._data[signalslice, start:stop]
            except StopIteration:
                return

    def __getitem__(self, idx):
        intervalslice, signalslice = self._parent._intervalsignalslicer[idx]

        interval_indices = self._parent._data_interval_indices()
        interval_indices = np.atleast_2d(interval_indices[intervalslice])

        if len(interval_indices) < 2:
            start, stop = interval_indices[0]
            return self._parent._data[signalslice, start:stop]
        else:
            return self._data_generator(interval_indices, signalslice)

    def plot_generator(self):
        interval_indices = self._parent._data_interval_indices()
        for start, stop in interval_indices:
            try:
                yield self._parent._data[:, start:stop]
            except StopIteration:
                return

    def __iter__(self):
        self._index = 0
        return self

    def __next__(self):
        index = self._index

        if index > self._parent.n_intervals - 1:
            raise StopIteration

        interval_indices = self._parent._data_interval_indices()
        interval_indices = interval_indices[index]
        start, stop = interval_indices

        self._index += 1

        return self._parent._data[:, start:stop]

IMUSensorArray

Bases: RegularlySampledAnalogSignalArray

Array for storing IMU (Inertial Measurement Unit) sensor data with regular sampling rates.

This class extends RegularlySampledAnalogSignalArray for IMU-specific data, such as accelerometer, gyroscope, and magnetometer signals.

Parameters:

Name Type Description Default
*args

Positional arguments passed to the parent class.

()
**kwargs

Keyword arguments passed to the parent class.

{}

Attributes:

Name Type Description
__aliases__ dict

Dictionary of class-specific aliases.

Examples:

>>> imu = IMUSensorArray(data=[[0, 1, 2], [3, 4, 5]], fs=100)
>>> imu.data
array([[0, 1, 2],
       [3, 4, 5]])
Source code in nelpy/core/_analogsignalarray.py
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
class IMUSensorArray(RegularlySampledAnalogSignalArray):
    """
    Array for storing IMU (Inertial Measurement Unit) sensor data with regular sampling rates.

    This class extends RegularlySampledAnalogSignalArray for IMU-specific data, such as accelerometer, gyroscope, and magnetometer signals.

    Parameters
    ----------
    *args :
        Positional arguments passed to the parent class.
    **kwargs :
        Keyword arguments passed to the parent class.

    Attributes
    ----------
    __aliases__ : dict
        Dictionary of class-specific aliases.

    Examples
    --------
    >>> imu = IMUSensorArray(data=[[0, 1, 2], [3, 4, 5]], fs=100)
    >>> imu.data
    array([[0, 1, 2],
           [3, 4, 5]])
    """

    # specify class-specific aliases:
    __aliases__ = {}

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

IntervalSignalSlicer

Bases: object

Slicer for extracting intervals and signals from analog signal arrays.

Parameters:

Name Type Description Default
obj object

The parent object to slice.

required
Source code in nelpy/core/_analogsignalarray.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class IntervalSignalSlicer(object):
    """
    Slicer for extracting intervals and signals from analog signal arrays.

    Parameters
    ----------
    obj : object
        The parent object to slice.
    """

    def __init__(self, obj):
        """
        Initialize the IntervalSignalSlicer.

        Parameters
        ----------
        obj : object
            The parent object to slice.
        """
        self.obj = obj

    def __getitem__(self, *args):
        """
        Extract intervals and signals based on the provided arguments.

        Parameters
        ----------
        *args : int, slice, or IntervalArray
            Indices or slices for intervals and signals.

        Returns
        -------
        intervalslice : int, slice, or IntervalArray
            The interval slice.
        signalslice : int or slice
            The signal slice.
        """
        # by default, keep all signals
        signalslice = 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, signal] slicing is supported at this time!"
                    )
                elif len(slices) == 2:
                    intervalslice, signalslice = slices
                else:
                    intervalslice = slices[0]
            except TypeError:
                # only interval to slice:
                intervalslice = slices

        return intervalslice, signalslice

MinimalExampleArray

Bases: RegularlySampledAnalogSignalArray

MinimalExampleArray is a custom example subclass of RegularlySampledAnalogSignalArray.

This class demonstrates how to extend RegularlySampledAnalogSignalArray with custom aliases and methods.

Parameters:

Name Type Description Default
*args

Positional arguments passed to the parent class.

()
**kwargs

Keyword arguments passed to the parent class.

{}

Attributes:

Name Type Description
__aliases__ dict

Dictionary of class-specific aliases.

Examples:

>>> arr = MinimalExampleArray(data=[[1, 2, 3]], fs=1000)
>>> arr.custom_func()
Woot! We have some special skillz!
Source code in nelpy/core/_analogsignalarray.py
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
class MinimalExampleArray(RegularlySampledAnalogSignalArray):
    """
    MinimalExampleArray is a custom example subclass of RegularlySampledAnalogSignalArray.

    This class demonstrates how to extend RegularlySampledAnalogSignalArray with custom aliases and methods.

    Parameters
    ----------
    *args :
        Positional arguments passed to the parent class.
    **kwargs :
        Keyword arguments passed to the parent class.

    Attributes
    ----------
    __aliases__ : dict
        Dictionary of class-specific aliases.

    Examples
    --------
    >>> arr = MinimalExampleArray(data=[[1, 2, 3]], fs=1000)
    >>> arr.custom_func()
    Woot! We have some special skillz!
    """

    # specify class-specific aliases:
    __aliases__ = {}

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

    def custom_func(self):
        """
        Print a custom message demonstrating a special method.

        Examples
        --------
        >>> arr = MinimalExampleArray(data=[[1, 2, 3]], fs=1000)
        >>> arr.custom_func()
        Woot! We have some special skillz!
        """
        print("Woot! We have some special skillz!")

custom_func()

Print a custom message demonstrating a special method.

Examples:

>>> arr = MinimalExampleArray(data=[[1, 2, 3]], fs=1000)
>>> arr.custom_func()
Woot! We have some special skillz!
Source code in nelpy/core/_analogsignalarray.py
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
def custom_func(self):
    """
    Print a custom message demonstrating a special method.

    Examples
    --------
    >>> arr = MinimalExampleArray(data=[[1, 2, 3]], fs=1000)
    >>> arr.custom_func()
    Woot! We have some special skillz!
    """
    print("Woot! We have some special skillz!")

PositionArray

Bases: AnalogSignalArray

An array for storing position data in 1D or 2D space.

PositionArray is a specialized subclass of AnalogSignalArray designed to handle position tracking data. It provides convenient access to x and y coordinates, supports both 1D and 2D positional data, and includes spatial boundary information.

Parameters:

Name Type Description Default
data array_like or None

Position data with shape (n_signals, n_samples). For 1D position data, n_signals should be 1. For 2D position data, n_signals should be 2, where the first row contains x-coordinates and the second row contains y-coordinates. Can also be specified using the alias 'posdata'.

required
timestamps array_like or None

Time stamps corresponding to each sample in data. If None, timestamps are automatically generated based on fs and start time.

required
fs float

Sampling frequency in Hz. Used to generate timestamps if not provided.

required
support EpochArray or None

EpochArray defining the time intervals over which the position data is valid.

required
label str

Descriptive label for the position array.

required
xlim tuple or None

Spatial boundaries for x-coordinate as (min_x, max_x).

required
ylim tuple or None

Spatial boundaries for y-coordinate as (min_y, max_y).

required

Attributes:

Name Type Description
x ndarray

X-coordinates as a 1D numpy array.

y ndarray

Y-coordinates as a 1D numpy array (only available for 2D data).

is_1d bool

True if position data is 1-dimensional.

is_2d bool

True if position data is 2-dimensional.

xlim tuple or None

Spatial boundaries for x-coordinate (only for 2D data).

ylim tuple or None

Spatial boundaries for y-coordinate (only for 2D data).

Examples:

Create a 1D position array:

>>> import numpy as np
>>> import nelpy as nel
>>> # 1D position data (e.g., position on a linear track)
>>> x_pos = np.linspace(0, 100, 1000)  # 100 cm track
>>> timestamps = np.linspace(0, 10, 1000)  # 10 seconds
>>> pos_1d = nel.PositionArray(
...     data=x_pos[np.newaxis, :],
...     timestamps=timestamps,
...     label="Linear track position",
... )
>>> print(f"1D position: {pos_1d.is_1d}")
>>> print(f"X range: {pos_1d.x.min():.1f} to {pos_1d.x.max():.1f} cm")

Create a 2D position array:

>>> # 2D position data (e.g., open field behavior)
>>> t = np.linspace(0, 2 * np.pi, 1000)
>>> x_pos = 50 + 30 * np.cos(t)  # circular trajectory
>>> y_pos = 50 + 30 * np.sin(t)
>>> pos_data = np.vstack([x_pos, y_pos])
>>> pos_2d = nel.PositionArray(
...     posdata=pos_data,
...     fs=100,  # 100 Hz sampling
...     xlim=(0, 100),
...     ylim=(0, 100),
...     label="Open field position",
... )
>>> print(f"2D position: {pos_2d.is_2d}")
>>> print(f"X position shape: {pos_2d.x.shape}")
>>> print(f"Y position shape: {pos_2d.y.shape}")
>>> print(f"Spatial bounds: x={pos_2d.xlim}, y={pos_2d.ylim}")

Access position data:

>>> # Get position at specific time
>>> time_idx = 500
>>> if pos_2d.is_2d:
...     x_at_time = pos_2d.x[time_idx]
...     y_at_time = pos_2d.y[time_idx]
...     print(f"Position at sample {time_idx}: ({x_at_time:.1f}, {y_at_time:.1f})")
Notes
  • For 2D position data, the first row of data should contain x-coordinates and the second row should contain y-coordinates.
  • The xlim and ylim parameters are only meaningful for 2D position data.
  • Attempting to access y-coordinates or spatial limits on 1D data will raise a ValueError.
  • The 'posdata' alias can be used interchangeably with 'data' parameter.
Source code in nelpy/core/_analogsignalarray.py
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
class PositionArray(AnalogSignalArray):
    """An array for storing position data in 1D or 2D space.

    PositionArray is a specialized subclass of AnalogSignalArray designed to
    handle position tracking data. It provides convenient access to x and y
    coordinates, supports both 1D and 2D positional data, and includes
    spatial boundary information.

    Parameters
    ----------
    data : array_like or None, optional
        Position data with shape (n_signals, n_samples). For 1D position data,
        n_signals should be 1. For 2D position data, n_signals should be 2,
        where the first row contains x-coordinates and the second row contains
        y-coordinates. Can also be specified using the alias 'posdata'.
    timestamps : array_like or None, optional
        Time stamps corresponding to each sample in data. If None, timestamps
        are automatically generated based on fs and start time.
    fs : float, optional
        Sampling frequency in Hz. Used to generate timestamps if not provided.
    support : EpochArray or None, optional
        EpochArray defining the time intervals over which the position data
        is valid.
    label : str, optional
        Descriptive label for the position array.
    xlim : tuple or None, optional
        Spatial boundaries for x-coordinate as (min_x, max_x).
    ylim : tuple or None, optional
        Spatial boundaries for y-coordinate as (min_y, max_y).

    Attributes
    ----------
    x : ndarray
        X-coordinates as a 1D numpy array.
    y : ndarray
        Y-coordinates as a 1D numpy array (only available for 2D data).
    is_1d : bool
        True if position data is 1-dimensional.
    is_2d : bool
        True if position data is 2-dimensional.
    xlim : tuple or None
        Spatial boundaries for x-coordinate (only for 2D data).
    ylim : tuple or None
        Spatial boundaries for y-coordinate (only for 2D data).

    Examples
    --------
    Create a 1D position array:

    >>> import numpy as np
    >>> import nelpy as nel
    >>> # 1D position data (e.g., position on a linear track)
    >>> x_pos = np.linspace(0, 100, 1000)  # 100 cm track
    >>> timestamps = np.linspace(0, 10, 1000)  # 10 seconds
    >>> pos_1d = nel.PositionArray(
    ...     data=x_pos[np.newaxis, :],
    ...     timestamps=timestamps,
    ...     label="Linear track position",
    ... )
    >>> print(f"1D position: {pos_1d.is_1d}")
    >>> print(f"X range: {pos_1d.x.min():.1f} to {pos_1d.x.max():.1f} cm")

    Create a 2D position array:

    >>> # 2D position data (e.g., open field behavior)
    >>> t = np.linspace(0, 2 * np.pi, 1000)
    >>> x_pos = 50 + 30 * np.cos(t)  # circular trajectory
    >>> y_pos = 50 + 30 * np.sin(t)
    >>> pos_data = np.vstack([x_pos, y_pos])
    >>> pos_2d = nel.PositionArray(
    ...     posdata=pos_data,
    ...     fs=100,  # 100 Hz sampling
    ...     xlim=(0, 100),
    ...     ylim=(0, 100),
    ...     label="Open field position",
    ... )
    >>> print(f"2D position: {pos_2d.is_2d}")
    >>> print(f"X position shape: {pos_2d.x.shape}")
    >>> print(f"Y position shape: {pos_2d.y.shape}")
    >>> print(f"Spatial bounds: x={pos_2d.xlim}, y={pos_2d.ylim}")

    Access position data:

    >>> # Get position at specific time
    >>> time_idx = 500
    >>> if pos_2d.is_2d:
    ...     x_at_time = pos_2d.x[time_idx]
    ...     y_at_time = pos_2d.y[time_idx]
    ...     print(f"Position at sample {time_idx}: ({x_at_time:.1f}, {y_at_time:.1f})")

    Notes
    -----
    - For 2D position data, the first row of data should contain x-coordinates
      and the second row should contain y-coordinates.
    - The xlim and ylim parameters are only meaningful for 2D position data.
    - Attempting to access y-coordinates or spatial limits on 1D data will
      raise a ValueError.
    - The 'posdata' alias can be used interchangeably with 'data' parameter.
    """

    # specify class-specific aliases:
    __aliases__ = {"posdata": "data"}

    def __init__(self, *args, **kwargs):
        # add class-specific aliases to existing aliases:
        self.__aliases__ = {**super().__aliases__, **self.__aliases__}
        xlim = kwargs.pop("xlim", None)
        ylim = kwargs.pop("ylim", None)
        super().__init__(*args, **kwargs)
        self._xlim = xlim
        self._ylim = ylim

    @property
    def is_2d(self):
        try:
            return self.n_signals == 2
        except IndexError:
            return False

    @property
    def is_1d(self):
        try:
            return self.n_signals == 1
        except IndexError:
            return False

    @property
    def x(self):
        """return x-values, as numpy array."""
        return self.data[0, :]

    @property
    def y(self):
        """return y-values, as numpy array."""
        if self.is_2d:
            return self.data[1, :]
        raise ValueError(
            "PositionArray is not 2 dimensional, so y-values are undefined!"
        )

    @property
    def xlim(self):
        if self.is_2d:
            return self._xlim
        raise ValueError(
            "PositionArray is not 2 dimensional, so xlim is not undefined!"
        )

    @xlim.setter
    def xlim(self, val):
        if self.is_2d:
            self._xlim = xlim  # noqa: F821
        raise ValueError(
            "PositionArray is not 2 dimensional, so xlim cannot be defined!"
        )

    @property
    def ylim(self):
        if self.is_2d:
            return self._ylim
        raise ValueError(
            "PositionArray is not 2 dimensional, so ylim is not undefined!"
        )

    @ylim.setter
    def ylim(self, val):
        if self.is_2d:
            self._ylim = ylim  # noqa: F821
        raise ValueError(
            "PositionArray is not 2 dimensional, so ylim cannot be defined!"
        )

x property

return x-values, as numpy array.

y property

return y-values, as numpy array.

RegularlySampledAnalogSignalArray

Continuous analog signal(s) with regular sampling rates (irregular sampling rates can be corrected with operations on the support) and same support. NOTE: data that is not equal dimensionality will NOT work and error/warning messages may/may not be sent out. Assumes abscissa_vals are identical for all signals passed through and are therefore expected to be 1-dimensional.

Parameters:

Name Type Description Default
data np.ndarray, with shape (n_signals, n_samples).

Data samples.

[]
abscissa_vals np.ndarray, with shape (n_samples, ).

The abscissa coordinate values. Currently we assume that (1) these values are timestamps, and (2) the timestamps are sampled regularly (we rely on these assumptions to generate intervals). Irregular sampling rates can be corrected with operations on the support.

None
fs float

The sampling rate. abscissa_vals are still expected to be in units of time and fs is expected to be in the corresponding sampling rate (e.g. abscissa_vals in seconds, fs in Hz). Default is 1 Hz.

None
step float

The sampling interval of the data, in seconds. Default is None. specifies step size of samples passed as tdata if fs is given, default is None. If not passed it is inferred by the minimum difference in between samples of tdata passed in (based on if FS is passed). e.g. decimated data would have sample numbers every ten samples so step=10

None
merge_sample_gap float

Optional merging of gaps between support intervals. If intervals are within a certain amount of time, gap, they will be merged as one interval. Example use case is when there is a dropped sample

0
support IntervalArray

Where the data are defined. Default is [0, last abscissa value] inclusive.

None
in_core bool

Whether the abscissa values should be treated as residing in core memory. During RSASA construction, np.diff() is called, so for large data, passing in in_core=True might help. In that case, a slower but much smaller memory footprint function is used.

True
labels np.array, dtype=np.str

Labels for each of the signals. If fewer labels than signals are passed in, labels are padded with None's to match the number of signals. If more labels than signals are passed in, labels are truncated to match the number of signals. Default is None.

None
empty bool

Return an empty RegularlySampledAnalogSignalArray if true else false. Default is false.

False
abscissa optional

The object handling the abscissa values. It is recommended to leave this parameter alone and let nelpy take care of this. Default is a nelpy.core.Abscissa object.

None
ordinate optional

The object handling the ordinate values. It is recommended to leave this parameter alone and let nelpy take care of this. Default is a nelpy.core.Ordinate object.

None

Attributes:

Name Type Description
data np.ndarray, with shape (n_signals, n_samples)

The underlying data.

abscissa_vals np.ndarray, with shape (n_samples, )

The values of the abscissa coordinate.

is1d bool

Whether there is only 1 signal in the RSASA

iswrapped bool

Whether the RSASA's data is wrapping.

base_unit string

Base unit of the abscissa.

signals list

A list of RegularlySampledAnalogSignalArrays, each RSASA containing a single signal (channel). WARNING: this method creates a copy of each signal, so is not particularly efficient at this time.

isreal bool

Whether ALL of the values in the RSASA's data are real.

iscomplex bool

Whether ANY values in the data are complex.

abs RegularlySampledAnalogSignalArray

A copy of the RSASA, whose data is the absolute value of the original original RSASA's (potentially complex) data.

phase RegularlySampledAnalogSignalArray

A copy of the RSASA, whose data is just the phase angle (in radians) of the original RSASA's data.

real RegularlySampledAnalogSignalArray

A copy of the RSASA, whose data is just the real part of the original RSASA's data.

imag RegularlySampledAnalogSignalArray

A copy of the RSASA, whose data is just the imaginary part of the original RSASA's data.

lengths list

The number of samples in each interval.

labels list

The labels corresponding to each signal.

n_signals int

The number of signals in the RSASA.

support IntervalArray

The support of the RSASA.

domain IntervalArray

The domain of the RSASA.

range IntervalArray

The range of the RSASA's data.

step float

The sampling interval of the RSASA. Currently the units are in seconds.

fs float

The sampling frequency of the RSASA. Currently the units are in Hz.

isempty bool

Whether the underlying data has zero length, i.e. 0 samples

n_bytes int

Approximate number of bytes taken up by the RSASA.

n_intervals int

The number of underlying intervals in the RSASA.

n_samples int

The number of abscissa values in the RSASA.

Source code in nelpy/core/_analogsignalarray.py
 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
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
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
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
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
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
class RegularlySampledAnalogSignalArray:
    """Continuous analog signal(s) with regular sampling rates (irregular
    sampling rates can be corrected with operations on the support) and same
    support. NOTE: data that is not equal dimensionality will NOT work
    and error/warning messages may/may not be sent out. Assumes abscissa_vals
    are identical for all signals passed through and are therefore expected
    to be 1-dimensional.

    Parameters
    ----------
    data : np.ndarray, with shape (n_signals, n_samples).
        Data samples.
    abscissa_vals : np.ndarray, with shape (n_samples, ).
        The abscissa coordinate values. Currently we assume that (1) these values
        are timestamps, and (2) the timestamps are sampled regularly (we rely on
        these assumptions to generate intervals). Irregular sampling rates can be
        corrected with operations on the support.
    fs : float, optional
        The sampling rate. abscissa_vals are still expected to be in units of
        time and fs is expected to be in the corresponding sampling rate (e.g.
        abscissa_vals in seconds, fs in Hz).
        Default is 1 Hz.
    step : float, optional
        The sampling interval of the data, in seconds.
        Default is None.
        specifies step size of samples passed as tdata if fs is given,
        default is None. If not passed it is inferred by the minimum
        difference in between samples of tdata passed in (based on if FS
        is passed). e.g. decimated data would have sample numbers every
        ten samples so step=10
    merge_sample_gap : float, optional
        Optional merging of gaps between support intervals. If intervals are within
        a certain amount of time, gap, they will be merged as one interval. Example
        use case is when there is a dropped sample
    support : nelpy.IntervalArray, optional
        Where the data are defined. Default is [0, last abscissa value] inclusive.
    in_core : bool, optional
        Whether the abscissa values should be treated as residing in core memory.
        During RSASA construction, np.diff() is called, so for large data, passing
        in in_core=True might help. In that case, a slower but much smaller memory
        footprint function is used.
    labels : np.array, dtype=np.str
        Labels for each of the signals. If fewer labels than signals are passed in,
        labels are padded with None's to match the number of signals. If more labels
        than signals are passed in, labels are truncated to match the number of
        signals.
        Default is None.
    empty : bool, optional
        Return an empty RegularlySampledAnalogSignalArray if true else false.
        Default is false.
    abscissa : optional
        The object handling the abscissa values. It is recommended to leave
        this parameter alone and let nelpy take care of this.
        Default is a nelpy.core.Abscissa object.
    ordinate : optional
        The object handling the ordinate values. It is recommended to leave
        this parameter alone and let nelpy take care of this.
        Default is a nelpy.core.Ordinate object.

    Attributes
    ----------
    data : np.ndarray, with shape (n_signals, n_samples)
        The underlying data.
    abscissa_vals : np.ndarray, with shape (n_samples, )
        The values of the abscissa coordinate.
    is1d : bool
        Whether there is only 1 signal in the RSASA
    iswrapped : bool
        Whether the RSASA's data is wrapping.
    base_unit : string
        Base unit of the abscissa.
    signals : list
        A list of RegularlySampledAnalogSignalArrays, each RSASA containing
        a single signal (channel).
        WARNING: this method creates a copy of each signal, so is not
        particularly efficient at this time.
    isreal : bool
        Whether ALL of the values in the RSASA's data are real.
    iscomplex : bool
        Whether ANY values in the data are complex.
    abs : nelpy.RegularlySampledAnalogSignalArray
        A copy of the RSASA, whose data is the absolute value of the original
        original RSASA's (potentially complex) data.
    phase : nelpy.RegularlySampledAnalogSignalArray
        A copy of the RSASA, whose data is just the phase angle (in radians) of
        the original RSASA's data.
    real : nelpy.RegularlySampledAnalogSignalArray
        A copy of the RSASA, whose data is just the real part of the original
        RSASA's data.
    imag : nelpy.RegularlySampledAnalogSignalArray
        A copy of the RSASA, whose data is just the imaginary part of the
        original RSASA's data.
    lengths : list
        The number of samples in each interval.
    labels : list
        The labels corresponding to each signal.
    n_signals : int
        The number of signals in the RSASA.
    support : nelpy.IntervalArray
        The support of the RSASA.
    domain : nelpy.IntervalArray
        The domain of the RSASA.
    range : nelpy.IntervalArray
        The range of the RSASA's data.
    step : float
        The sampling interval of the RSASA. Currently the units are
        in seconds.
    fs : float
        The sampling frequency of the RSASA. Currently the units are
        in Hz.
    isempty : bool
        Whether the underlying data has zero length, i.e. 0 samples
    n_bytes : int
        Approximate number of bytes taken up by the RSASA.
    n_intervals : int
        The number of underlying intervals in the RSASA.
    n_samples : int
        The number of abscissa values in the RSASA.
    """

    __aliases__ = {}

    __attributes__ = [
        "_data",
        "_abscissa_vals",
        "_fs",
        "_support",
        "_interp",
        "_step",
        "_labels",
    ]

    @rsasa_init_wrapper
    def __init__(
        self,
        data=[],
        *,
        abscissa_vals=None,
        fs=None,
        step=None,
        merge_sample_gap=0,
        support=None,
        in_core=True,
        labels=None,
        empty=False,
        abscissa=None,
        ordinate=None,
    ):
        self._intervalsignalslicer = IntervalSignalSlicer(self)
        self._intervaldata = DataSlicer(self)
        self._intervaltime = AbscissaSlicer(self)

        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

        # TODO: #FIXME abscissa and ordinate domain, range, and supports should be integrated and/or coerced with support

        self.__version__ = version.__version__

        # cast derivatives of RegularlySampledAnalogSignalArray back into RegularlySampledAnalogSignalArray:
        # if isinstance(data, auxiliary.PositionArray):
        if isinstance(data, RegularlySampledAnalogSignalArray):
            self.__dict__ = copy.deepcopy(data.__dict__)
            # if self._has_changed:
            # self.__renew__()
            self.__renew__()
            return

        if empty:
            for attr in self.__attributes__:
                exec("self." + attr + " = None")
            self._abscissa.support = type(self._abscissa.support)(empty=True)
            self._data = np.array([])
            self._abscissa_vals = np.array([])
            self.__bake__()
            return

        self._step = step
        self._fs = fs

        # Note; if we have an empty array of data with no dimension,
        # then calling len(data) will return a TypeError
        try:
            # if no data are given return empty RegularlySampledAnalogSignalArray
            if data.size == 0:
                self.__init__(empty=True)
                return
        except TypeError:
            logging.warning(
                "unsupported type; creating empty RegularlySampledAnalogSignalArray"
            )
            self.__init__(empty=True)
            return

        # Note: if both abscissa_vals and data are given and dimensionality does not
        # match, then TypeError!

        abscissa_vals = np.squeeze(abscissa_vals).astype(float)
        if abscissa_vals.shape[0] != data.shape[1]:
            # self.__init__([],empty=True)
            raise TypeError(
                "abscissa_vals and data size mismatch! Note: data "
                "is expected to have rows containing signals"
            )
        # data is not sorted and user wants it to be
        # TODO: use faster is_sort from jagular
        if not utils.is_sorted(abscissa_vals):
            logging.warning("Data is _not_ sorted! Data will be sorted automatically.")
            ind = np.argsort(abscissa_vals)
            abscissa_vals = abscissa_vals[ind]
            data = np.take(a=data, indices=ind, axis=-1)

        self._data = data
        self._abscissa_vals = abscissa_vals

        # handle labels
        if labels is not None:
            labels = np.asarray(labels, dtype=str)
            # label size doesn't match
            if labels.shape[0] > data.shape[0]:
                logging.warning(
                    "More labels than data! Labels are truncated to size of data"
                )
                labels = labels[0 : data.shape[0]]
            elif labels.shape[0] < data.shape[0]:
                logging.warning(
                    "Fewer labels than abscissa_vals! Labels are filled with "
                    "None to match data shape"
                )
                for i in range(labels.shape[0], data.shape[0]):
                    labels.append(None)
        self._labels = labels

        # Alright, let's handle all the possible parameter cases!
        if support is not None:
            self._restrict_to_interval_array_fast(intervalarray=support)
        else:
            logging.warning(
                "creating support from abscissa_vals and sampling rate, fs!"
            )
            self._abscissa.support = type(self._abscissa.support)(
                utils.get_contiguous_segments(
                    self._abscissa_vals, step=self._step, fs=fs, in_core=in_core
                )
            )
            if merge_sample_gap > 0:
                self._abscissa.support = self._abscissa.support.merge(
                    gap=merge_sample_gap
                )

        if np.abs((self.fs - self._estimate_fs()) / self.fs) > 0.01:
            logging.warning("estimated fs and provided fs differ by more than 1%")

    def __bake__(self):
        """Fix object as-is, and bake a new hash.

        For example, if a label has changed, or if an interp has been attached,
        then the object's hash will change, and it needs to be baked
        again for efficiency / consistency.
        """
        self._stored_hash_ = self.__hash__()

    # def _has_changed_data(self):
    #     """Compute hash on abscissa_vals and data and compare to cached hash."""
    #     return self.data.__hash__ elf._data_hash_

    def _has_changed(self):
        """Compute hash on current object, and compare to previously stored hash"""
        return self.__hash__() == self._stored_hash_

    def __renew__(self):
        """Re-attach data slicers."""
        self._intervalsignalslicer = IntervalSignalSlicer(self)
        self._intervaldata = DataSlicer(self)
        self._intervaltime = AbscissaSlicer(self)
        self._interp = None
        self.__bake__()

    def __call__(self, x):
        """RegularlySampledAnalogSignalArray callable method. Returns
        interpolated data at requested points. Note that points falling
        outside the support will not be interpolated.

        Parameters
        ----------
        x : np.ndarray, list, or tuple, with length n_requested_samples
            Points at which to interpolate the RSASA's data

        Returns
        -------
        A np.ndarray with shape (n_signals, n_samples). If all the requested
        points lie in the support, then n_samples = n_requested_samples.
        Otherwise n_samples < n_requested_samples.
        """

        return self.asarray(at=x).yvals

    def center(self, inplace=False):
        """
        Center the data to have zero mean along the sample axis.

        Parameters
        ----------
        inplace : bool, optional
            If True, modifies the data in place. If False (default), returns a new object.

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            The centered signal array.

        Examples
        --------
        >>> centered = asa.center()
        >>> centered.mean()
        0.0
        """
        if inplace:
            out = self
        else:
            out = self.copy()
        out._data = (out._data.T - out.mean()).T
        return out

    def normalize(self, inplace=False):
        """
        Normalize the data to have unit standard deviation along the sample axis.

        Parameters
        ----------
        inplace : bool, optional
            If True, modifies the data in place. If False (default), returns a new object.

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            The normalized signal array.

        Examples
        --------
        >>> normalized = asa.normalize()
        >>> normalized.std()
        1.0
        """
        if inplace:
            out = self
        else:
            out = self.copy()
        std = np.atleast_1d(out.std())
        std[std == 0] = 1
        out._data = (out._data.T / std).T
        return out

    def standardize(self, inplace=False):
        """
        Standardize the data to zero mean and unit standard deviation along the sample axis.

        Parameters
        ----------
        inplace : bool, optional
            If True, modifies the data in place. If False (default), returns a new object.

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            The standardized signal array.

        Examples
        --------
        >>> standardized = asa.standardize()
        >>> standardized.mean(), standardized.std()
        (0.0, 1.0)
        """
        if inplace:
            out = self
        else:
            out = self.copy()
        out._data = (out._data.T - out.mean()).T
        std = np.atleast_1d(out.std())
        std[std == 0] = 1
        out._data = (out._data.T / std).T
        return out

    @property
    def is_1d(self):
        try:
            return self.n_signals == 1
        except IndexError:
            return False

    @property
    def is_wrapped(self):
        if np.any(self.max() > self._ordinate.range.stop) | np.any(
            self.min() < self._ordinate.range.min
        ):
            self._ordinate._is_wrapped = False
        else:
            self._ordinate._is_wrapped = True

        # if self._ordinate._is_wrapped is None:
        #     if np.any(self.max() > self._ordinate.range.stop) | np.any(self.min() < self._ordinate.range.min):
        #         self._ordinate._is_wrapped = False
        #     else:
        #         self._ordinate._is_wrapped = True
        return self._ordinate._is_wrapped

    def _wrap(self, arr, vmin, vmax):
        """Wrap array within finite range."""
        if np.isinf(vmax - vmin):
            raise ValueError("range has to be finite!")
        return ((arr - vmin) % (vmax - vmin)) + vmin

    def wrap(self, inplace=False):
        """
        Wrap the ordinate values within the finite range defined by the ordinate's range.

        Parameters
        ----------
        inplace : bool, optional
            If True, modifies the data in place. If False (default), returns a new object.

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            The wrapped signal array.

        Examples
        --------
        >>> wrapped = asa.wrap()
        """
        if inplace:
            out = self
        else:
            out = self.copy()

        out.data = np.atleast_2d(
            out._wrap(out.data, out._ordinate.range.min, out._ordinate.range.max)
        )
        # out._is_wrapped = True
        return out

    def _unwrap(self, arr, vmin, vmax):
        """Unwrap 2D array (with one signal per row) by minimizing total displacement."""
        d = vmax - vmin
        dh = d / 2

        lin = copy.deepcopy(arr) - vmin
        n_signals, n_samples = arr.shape
        for ii in range(1, n_samples):
            h1 = lin[:, ii] - lin[:, ii - 1] >= dh
            lin[h1, ii:] = lin[h1, ii:] - d
            h2 = lin[:, ii] - lin[:, ii - 1] < -dh
            lin[h2, ii:] = lin[h2, ii:] + d
        return np.atleast_2d(lin + vmin)

    def unwrap(self, inplace=False):
        """
        Unwrap the ordinate values by minimizing total displacement, useful for phase data.

        Parameters
        ----------
        inplace : bool, optional
            If True, modifies the data in place. If False (default), returns a new object.

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            The unwrapped signal array.

        Examples
        --------
        >>> unwrapped = asa.unwrap()
        """
        if inplace:
            out = self
        else:
            out = self.copy()

        out.data = np.atleast_2d(
            out._unwrap(out._data, out._ordinate.range.min, out._ordinate.range.max)
        )
        # out._is_wrapped = False
        return out

    def _crossvals(self):
        """Return all abscissa values where the orinate crosses.

        Note that this can return multiple values close in succession
        if the signal oscillates around the maximum or minimum range.
        """
        raise NotImplementedError

    @property
    def base_unit(self):
        """Base unit of the abscissa."""
        return self._abscissa.base_unit

    def _data_interval_indices(self):
        """
        Get the start and stop indices for each interval in the analog signal array.

        Returns
        -------
        indices : np.ndarray
            Array of shape (n_intervals, 2), where each row contains the start and stop indices for an interval.
        """
        tmp = np.insert(np.cumsum(self.lengths), 0, 0)
        indices = np.vstack((tmp[:-1], tmp[1:])).T
        return indices

    def ddt(self, rectify=False):
        """Returns the derivative of each signal in the RegularlySampledAnalogSignalArray.

        asa.data = f(t)
        asa.ddt = d/dt (asa.data)

        Parameters
        ----------
        rectify : boolean, optional
            If True, the absolute value of the derivative will be returned.
            Default is False.

        Returns
        -------
        ddt : RegularlySampledAnalogSignalArray
            Time derivative of each signal in the RegularlySampledAnalogSignalArray.

        Note
        ----
        Second order central differences are used here, and it is assumed that
        the signals are sampled uniformly. If the signals are not uniformly
        sampled, it is recommended to resample the signal before computing the
        derivative.
        """
        ddt = utils.ddt_asa(self, rectify=rectify)
        return ddt

    @property
    def signals(self):
        """Returns a list of RegularlySampledAnalogSignalArrays, each array containing
        a single signal (channel).

        WARNING: this method creates a copy of each signal, so is not
        particularly efficient at this time.

        Examples
        --------
        >>> for channel in lfp.signals:
            print(channel)
        """
        signals = []
        for ii in range(self.n_signals):
            signals.append(self[:, ii])
        return signals
        # return np.asanyarray(signals).squeeze()

    @property
    def isreal(self):
        """Returns True if entire signal is real."""
        return np.all(np.isreal(self.data))
        # return np.isrealobj(self._data)

    @property
    def iscomplex(self):
        """Returns True if any part of the signal is complex."""
        return np.any(np.iscomplex(self.data))
        # return np.iscomplexobj(self._data)

    @property
    def abs(self):
        """RegularlySampledAnalogSignalArray with absolute value of (potentially complex) data."""
        out = self.copy()
        out._data = np.abs(self.data)
        return out

    @property
    def angle(self):
        """RegularlySampledAnalogSignalArray with only phase angle (in radians) of data."""
        out = self.copy()
        out._data = np.angle(self.data)
        return out

    @property
    def imag(self):
        """RegularlySampledAnalogSignalArray with only imaginary part of data."""
        out = self.copy()
        out._data = self.data.imag
        return out

    @property
    def real(self):
        """RegularlySampledAnalogSignalArray with only real part of data."""
        out = self.copy()
        out._data = self.data.real
        return out

    def __mul__(self, other):
        """overloaded * operator."""
        if isinstance(other, numbers.Number):
            newasa = self.copy()
            newasa._data = self.data * other
            return newasa
        elif isinstance(other, np.ndarray):
            newasa = self.copy()
            newasa._data = (self.data.T * other).T
            return newasa
        elif isinstance(other, RegularlySampledAnalogSignalArray):
            if (
                self.data.shape != other.data.shape
                or not np.allclose(self.abscissa_vals, other.abscissa_vals)
                or self.fs != other.fs
            ):
                raise ValueError(
                    "AnalogSignalArrays must have the same shape, abscissa_vals, and fs to multiply."
                )
            newasa = self.copy()
            newasa._data = self.data * other.data
            return newasa
        else:
            raise TypeError(
                "unsupported operand type(s) for *: 'RegularlySampledAnalogSignalArray' and '{}'".format(
                    str(type(other))
                )
            )

    def __add__(self, other):
        """overloaded + operator."""
        if isinstance(other, numbers.Number):
            newasa = self.copy()
            newasa._data = self.data + other
            return newasa
        elif isinstance(other, np.ndarray):
            newasa = self.copy()
            newasa._data = (self.data.T + other).T
            return newasa
        elif isinstance(other, RegularlySampledAnalogSignalArray):
            if (
                self.data.shape != other.data.shape
                or not np.allclose(self.abscissa_vals, other.abscissa_vals)
                or self.fs != other.fs
            ):
                raise ValueError(
                    "AnalogSignalArrays must have the same shape, abscissa_vals, and fs to add."
                )
            newasa = self.copy()
            newasa._data = self.data + other.data
            return newasa
        else:
            raise TypeError(
                "unsupported operand type(s) for +: 'RegularlySampledAnalogSignalArray' and '{}'".format(
                    str(type(other))
                )
            )

    def __sub__(self, other):
        """overloaded - operator."""
        if isinstance(other, numbers.Number):
            newasa = self.copy()
            newasa._data = self.data - other
            return newasa
        elif isinstance(other, np.ndarray):
            newasa = self.copy()
            newasa._data = (self.data.T - other).T
            return newasa
        elif isinstance(other, RegularlySampledAnalogSignalArray):
            if (
                self.data.shape != other.data.shape
                or not np.allclose(self.abscissa_vals, other.abscissa_vals)
                or self.fs != other.fs
            ):
                raise ValueError(
                    "AnalogSignalArrays must have the same shape, abscissa_vals, and fs to subtract."
                )
            newasa = self.copy()
            newasa._data = self.data - other.data
            return newasa
        else:
            raise TypeError(
                "unsupported operand type(s) for -: 'RegularlySampledAnalogSignalArray' and '{}'".format(
                    str(type(other))
                )
            )

    def zscore(self):
        """
        Normalize each signal in the array using z-scores (zero mean, unit variance).

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            New object with z-scored data.

        Examples
        --------
        >>> zscored = asa.zscore()
        """
        out = self.copy()
        out._data = zscore(out._data, axis=1)
        return out

    def __truediv__(self, other):
        """overloaded / operator."""
        if isinstance(other, numbers.Number):
            newasa = self.copy()
            newasa._data = self.data / other
            return newasa
        elif isinstance(other, np.ndarray):
            newasa = self.copy()
            newasa._data = (self.data.T / other).T
            return newasa
        elif isinstance(other, RegularlySampledAnalogSignalArray):
            if (
                self.data.shape != other.data.shape
                or not np.allclose(self.abscissa_vals, other.abscissa_vals)
                or self.fs != other.fs
            ):
                raise ValueError(
                    "AnalogSignalArrays must have the same shape, abscissa_vals, and fs to divide."
                )
            newasa = self.copy()
            newasa._data = self.data / other.data
            return newasa
        else:
            raise TypeError(
                "unsupported operand type(s) for /: 'RegularlySampledAnalogSignalArray' and '{}'".format(
                    str(type(other))
                )
            )

    def __rmul__(self, other):
        return self.__mul__(other)

    def __lshift__(self, val):
        """shift abscissa and support to left (<<)"""
        if isinstance(val, numbers.Number):
            new = self.copy()
            new._abscissa_vals -= val
            new._abscissa.support = new._abscissa.support << val
            return new
        else:
            raise TypeError(
                "unsupported operand type(s) for <<: {} and {}".format(
                    str(type(self)), str(type(val))
                )
            )

    def __rshift__(self, val):
        """shift abscissa and support to right (>>)"""
        if isinstance(val, numbers.Number):
            new = self.copy()
            new._abscissa_vals += val
            new._abscissa.support = new._abscissa.support >> val
            return new
        else:
            raise TypeError(
                "unsupported operand type(s) for >>: {} and {}".format(
                    str(type(self)), str(type(val))
                )
            )

    def __len__(self):
        return self.n_intervals

    def _drop_empty_intervals(self):
        """Drops empty intervals from support. In-place."""
        keep_interval_ids = np.argwhere(self.lengths).squeeze().tolist()
        self._abscissa.support = self._abscissa.support[keep_interval_ids]
        return self

    def _estimate_fs(self, abscissa_vals=None):
        """Estimate the sampling rate of the data."""
        if abscissa_vals is None:
            abscissa_vals = self._abscissa_vals
        return 1.0 / np.median(np.diff(abscissa_vals))

    def downsample(self, *, fs_out, aafilter=True, inplace=False, **kwargs):
        """Downsamples the RegularlySampledAnalogSignalArray

        Parameters
        ----------
        fs_out : float, optional
            Desired output sampling rate in Hz
        aafilter : boolean, optional
            Whether to apply an anti-aliasing filter before performing the actual
            downsampling. Default is True
        inplace : boolean, optional
            If True, the output ASA will replace the input ASA. Default is False
        kwargs :
            Other keyword arguments are passed to sosfiltfilt() in the `filtering`
            module

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            The downsampled RegularlySampledAnalogSignalArray
        """

        if not fs_out < self._fs:
            raise ValueError("fs_out must be less than current sampling rate!")

        if aafilter:
            fh = fs_out / 2.0
            out = filtering.sosfiltfilt(self, fl=None, fh=fh, inplace=inplace, **kwargs)

        downsampled = out.simplify(ds=1 / fs_out)
        out._data = downsampled._data
        out._abscissa_vals = downsampled._abscissa_vals
        out._fs = fs_out

        out.__renew__()
        return out

    def add_signal(self, signal, label=None):
        """Docstring goes here.
        Basically we add a signal, and we add a label. THIS HAPPENS IN PLACE?
        """
        # TODO: add functionality to check that supports are the same, etc.
        if isinstance(signal, RegularlySampledAnalogSignalArray):
            signal = signal.data

        signal = np.squeeze(signal)
        if signal.ndim > 1:
            raise TypeError("Can only add one signal at a time!")
        if self.data.ndim == 1:
            self._data = np.vstack(
                [np.array(self.data, ndmin=2), np.array(signal, ndmin=2)]
            )
        else:
            self._data = np.vstack([self.data, np.array(signal, ndmin=2)])
        if label is None:
            logging.warning("None label appended")
        self._labels = np.append(self._labels, label)
        return self

    def _restrict_to_interval_array_fast(self, *, intervalarray=None, update=True):
        """Restrict self._abscissa_vals and self._data to an IntervalArray. If no
        IntervalArray is specified, self._abscissa.support is used.

        Parameters
        ----------
        intervalarray : IntervalArray, optional
                IntervalArray on which to restrict AnalogSignal. Default is
                self._abscissa.support
        update : bool, optional
                Overwrite self._abscissa.support with intervalarray if True (default).
        """
        if intervalarray is None:
            intervalarray = self._abscissa.support
            update = False  # support did not change; no need to update

        try:
            if intervalarray.isempty:
                logging.warning("Support specified is empty")
                # self.__init__([],empty=True)
                exclude = ["_support", "_data", "_fs", "_step"]
                attrs = (x for x in self.__attributes__ if x not in exclude)
                logging.disable(logging.CRITICAL)
                for attr in attrs:
                    exec("self." + attr + " = None")
                logging.disable(0)
                self._data = np.zeros([0, self.data.shape[0]])
                self._data[:] = np.nan
                self._abscissa.support = intervalarray
                return
        except AttributeError:
            raise AttributeError("IntervalArray expected")

        indices = []
        for interval in intervalarray.merge().data:
            a_start = interval[0]
            a_stop = interval[1]
            frm, to = np.searchsorted(self._abscissa_vals, (a_start, a_stop + 1e-10))
            indices.append((frm, to))
        indices = np.array(indices, ndmin=2)
        if np.diff(indices).sum() < len(self._abscissa_vals):
            logging.warning("ignoring signal outside of support")
        # check if only one interval and interval is already bounds of data
        # if so, we don't need to do anything
        if len(indices) == 1:
            if indices[0, 0] == 0 and indices[0, 1] == len(self._abscissa_vals):
                if update:
                    self._abscissa.support = intervalarray
                    return
        try:
            data_list = []
            for start, stop in indices:
                data_list.append(self._data[:, start:stop])
            self._data = np.hstack(data_list)
        except IndexError:
            self._data = np.zeros([0, self.data.shape[0]])
            self._data[:] = np.nan
        time_list = []
        for start, stop in indices:
            time_list.extend(self._abscissa_vals[start:stop])
        self._abscissa_vals = np.array(time_list)
        if update:
            self._abscissa.support = intervalarray

    def _restrict_to_interval_array(self, *, intervalarray=None, update=True):
        """Restrict self._abscissa_vals and self._data to an IntervalArray. If no
        IntervalArray is specified, self._abscissa.support is used.

        This function is quite slow, as it checks each sample for inclusion.
        It does this in a vectorized form, which is fast for small or moderately
        sized objects, but the memory penalty can be large, and it becomes very
        slow for large objects. Consequently, _restrict_to_interval_array_fast
        should be used when possible.

        Parameters
        ----------
        intervalarray : IntervalArray, optional
                IntervalArray on which to restrict AnalogSignal. Default is
                self._abscissa.support
        update : bool, optional
                Overwrite self._abscissa.support with intervalarray if True (default).
        """
        if intervalarray is None:
            intervalarray = self._abscissa.support
            update = False  # support did not change; no need to update

        try:
            if intervalarray.isempty:
                logging.warning("Support specified is empty")
                # self.__init__([],empty=True)
                exclude = ["_support", "_data", "_fs", "_step"]
                attrs = (x for x in self.__attributes__ if x not in exclude)
                logging.disable(logging.CRITICAL)
                for attr in attrs:
                    exec("self." + attr + " = None")
                logging.disable(0)
                self._data = np.zeros([0, self.data.shape[0]])
                self._data[:] = np.nan
                self._abscissa.support = intervalarray
                return
        except AttributeError:
            raise AttributeError("IntervalArray expected")

        indices = []
        for interval in intervalarray.merge().data:
            a_start = interval[0]
            a_stop = interval[1]
            indices.append(
                (self._abscissa_vals >= a_start) & (self._abscissa_vals < a_stop)
            )
        indices = np.any(np.column_stack(indices), axis=1)
        if np.count_nonzero(indices) < len(self._abscissa_vals):
            logging.warning("ignoring signal outside of support")
        try:
            self._data = self.data[:, indices]
        except IndexError:
            self._data = np.zeros([0, self.data.shape[0]])
            self._data[:] = np.nan
        self._abscissa_vals = self._abscissa_vals[indices]
        if update:
            self._abscissa.support = intervalarray

    @keyword_deprecation(replace_x_with_y={"bw": "truncate"})
    def smooth(
        self,
        *,
        fs=None,
        sigma=None,
        truncate=None,
        inplace=False,
        mode=None,
        cval=None,
        within_intervals=False,
    ):
        """Smooths the regularly sampled RegularlySampledAnalogSignalArray with a Gaussian kernel.

        Smoothing is applied along the abscissa, and the same smoothing is applied to each
        signal in the RegularlySampledAnalogSignalArray, or to each unit in a BinnedSpikeTrainArray.

        Smoothing is applied ACROSS intervals, but smoothing WITHIN intervals is also supported.

        Parameters
        ----------
        obj : RegularlySampledAnalogSignalArray or BinnedSpikeTrainArray.
        fs : float, optional
            Sampling rate (in obj.base_unit^-1) of obj. If not provided, it will
            be inferred.
        sigma : float, optional
            Standard deviation of Gaussian kernel, in obj.base_units. Default is 0.05
            (50 ms if base_unit=seconds).
        truncate : float, optional
            Bandwidth outside of which the filter value will be zero. Default is 4.0.
        inplace : bool
            If True the data will be replaced with the smoothed data.
            Default is False.
        mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
            The mode parameter determines how the array borders are handled,
            where cval is the value when mode is equal to 'constant'. Default is
            'reflect'.
        cval : scalar, optional
            Value to fill past edges of input if mode is 'constant'. Default is 0.0.
        within_intervals : boolean, optional
            If True, then smooth within each epoch. Otherwise smooth across epochs.
            Default is False.
            Note that when mode = 'wrap', then smoothing within epochs aren't affected
            by wrapping.

        Returns
        -------
        out : same type as obj
            An object with smoothed data is returned.

        """

        if sigma is None:
            sigma = 0.05
        if truncate is None:
            truncate = 4

        kwargs = {
            "inplace": inplace,
            "fs": fs,
            "sigma": sigma,
            "truncate": truncate,
            "mode": mode,
            "cval": cval,
            "within_intervals": within_intervals,
        }

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

        if self._ordinate.is_wrapping:
            ord_is_wrapped = self.is_wrapped

            if ord_is_wrapped:
                out = out.unwrap()

        # case 1: abs.wrapping=False, ord.linking=False, ord.wrapping=False
        if (
            not self._abscissa.is_wrapping
            and not self._ordinate.is_linking
            and not self._ordinate.is_wrapping
        ):
            pass

        # case 2: abs.wrapping=False, ord.linking=False, ord.wrapping=True
        elif (
            not self._abscissa.is_wrapping
            and not self._ordinate.is_linking
            and self._ordinate.is_wrapping
        ):
            pass

        # case 3: abs.wrapping=False, ord.linking=True, ord.wrapping=False
        elif (
            not self._abscissa.is_wrapping
            and self._ordinate.is_linking
            and not self._ordinate.is_wrapping
        ):
            raise NotImplementedError

        # case 4: abs.wrapping=False, ord.linking=True, ord.wrapping=True
        elif (
            not self._abscissa.is_wrapping
            and self._ordinate.is_linking
            and self._ordinate.is_wrapping
        ):
            raise NotImplementedError

        # case 5: abs.wrapping=True, ord.linking=False, ord.wrapping=False
        elif (
            self._abscissa.is_wrapping
            and not self._ordinate.is_linking
            and not self._ordinate.is_wrapping
        ):
            if mode is None:
                kwargs["mode"] = "wrap"

        # case 6: abs.wrapping=True, ord.linking=False, ord.wrapping=True
        elif (
            self._abscissa.is_wrapping
            and not self._ordinate.is_linking
            and self._ordinate.is_wrapping
        ):
            # (1) unwrap ordinate (abscissa wrap=False)
            # (2) smooth unwrapped ordinate (absissa wrap=False)
            # (3) repeat unwrapped signal based on conditions from (2):
            # if smoothed wrapped ordinate samples
            # HH ==> SSS (this must be done on a per-signal basis!!!) H = high; L = low; S = same
            # LL ==> SSS (the vertical offset must be such that neighbors have smallest displacement)
            # LH ==> LSH
            # HL ==> HSL
            # (4) smooth expanded and unwrapped ordinate (abscissa wrap=False)
            # (5) cut out orignal signal

            # (1)
            kwargs["mode"] = "reflect"
            L = out._ordinate.range.max - out._ordinate.range.min
            D = out.domain.length

            tmp = utils.gaussian_filter(out.unwrap(), **kwargs)
            # (2) (3)
            n_reps = int(np.ceil((sigma * truncate) / float(D)))

            smooth_data = []
            for ss, signal in enumerate(tmp.signals):
                # signal = signal.wrap()
                offset = (
                    float((signal._data[:, -1] - signal._data[:, 0]) // (L / 2)) * L
                )
                # print(offset)
                # left_high = signal._data[:,0] >= out._ordinate.range.min + L/2
                # right_high = signal._data[:,-1] >= out._ordinate.range.min + L/2
                # signal = signal.unwrap()

                expanded = signal.copy()
                for nn in range(n_reps):
                    expanded = expanded.join((signal << D * (nn + 1)) - offset).join(
                        (signal >> D * (nn + 1)) + offset
                    )
                    # print(expanded)
                    # if left_high == right_high:
                    #     print('extending flat! signal {}'.format(ss))
                    #     expanded = expanded.join(signal << D*(nn+1)).join(signal >> D*(nn+1))
                    # elif left_high < right_high:
                    #     print('extending LSH! signal {}'.format(ss))
                    #     # LSH
                    #     expanded = expanded.join((signal << D*(nn+1))-L).join((signal >> D*(nn+1))+L)
                    # else:
                    #     # HSL
                    #     print('extending HSL! signal {}'.format(ss))
                    #     expanded = expanded.join((signal << D*(nn+1))+L).join((signal >> D*(nn+1))-L)
                # (4)
                smooth_signal = utils.gaussian_filter(expanded, **kwargs)
                smooth_data.append(
                    smooth_signal._data[
                        :, n_reps * tmp.n_samples : (n_reps + 1) * (tmp.n_samples)
                    ].squeeze()
                )
            # (5)
            out._data = np.array(smooth_data)
            out.__renew__()

            if self._ordinate.is_wrapping:
                if ord_is_wrapped:
                    out = out.wrap()

            return out

        # case 7: abs.wrapping=True, ord.linking=True, ord.wrapping=False
        elif (
            self._abscissa.is_wrapping
            and self._ordinate.is_linking
            and not self._ordinate.is_wrapping
        ):
            raise NotImplementedError

        # case 8: abs.wrapping=True, ord.linking=True, ord.wrapping=True
        elif (
            self._abscissa.is_wrapping
            and self._ordinate.is_linking
            and self._ordinate.is_wrapping
        ):
            raise NotImplementedError

        out = utils.gaussian_filter(out, **kwargs)
        out.__renew__()

        if self._ordinate.is_wrapping:
            if ord_is_wrapped:
                out = out.wrap()

        return out

    @property
    def lengths(self):
        """(list) The number of samples in each interval."""
        indices = []
        for interval in self.support.data:
            a_start = interval[0]
            a_stop = interval[1]
            frm, to = np.searchsorted(self._abscissa_vals, (a_start, a_stop))
            indices.append((frm, to))
        indices = np.array(indices, ndmin=2)
        lengths = np.atleast_1d(np.diff(indices).squeeze())
        return lengths

    @property
    def labels(self):
        """(list) The labels corresponding to each signal."""
        # TODO: make this faster and better!
        return self._labels

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

    def __repr__(self):
        address_str = " at " + str(hex(id(self)))
        if self.isempty:
            return "<empty " + self.type_name + address_str + ">"
        if self.n_intervals > 1:
            epstr = " ({} segments)".format(self.n_intervals)
        else:
            epstr = ""
        try:
            if self.n_signals > 0:
                nstr = " %s signals%s" % (self.n_signals, epstr)
        except IndexError:
            nstr = " 1 signal%s" % epstr
        dstr = " for a total of {}".format(
            self._abscissa.formatter(self.support.length)
        )
        return "<%s%s:%s>%s" % (self.type_name, address_str, nstr, dstr)

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

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

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            RegularlySampledAnalogSignalArray 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_samples or ds to be violated.
        """

        out = self.copy()
        out._abscissa.support = out.support.partition(ds=ds, n_intervals=n_intervals)
        return out

    # @property
    # def ydata(self):
    #     """(np.array N-Dimensional) data with shape (n_signals, n_samples)."""
    #     # LEGACY
    #     return self.data

    @property
    def data(self):
        """(np.array N-Dimensional) data with shape (n_signals, n_samples)."""
        return self._data

    @data.setter
    def data(self, val):
        """(np.array N-Dimensional) data with shape (n_signals, n_samples)."""
        self._data = val
        # print('data was modified, so clearing interp, etc.')
        self.__renew__()

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

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

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

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

    @property
    def range(self):
        """(nelpy.IntervalArray) The range of the underlying RegularlySampledAnalogSignalArray."""
        return self._ordinate.range

    @range.setter
    def range(self, val):
        """(nelpy.IntervalArray) The range of the underlying RegularlySampledAnalogSignalArray."""
        # modify range
        self._ordinate.range = val

    @property
    def step(self):
        """steps per sample
        Example 1: sample_numbers = np.array([1,2,3,4,5,6]) #aka time
        Steps per sample in the above case would be 1

        Example 2: sample_numbers = np.array([1,3,5,7,9]) #aka time
        Steps per sample in Example 2 would be 2
        """
        return self._step

    @property
    def abscissa_vals(self):
        """(np.array 1D) Time in seconds."""
        return self._abscissa_vals

    @abscissa_vals.setter
    def abscissa_vals(self, vals):
        """(np.array 1D) Time in seconds."""
        self._abscissa_vals = vals

    @property
    def fs(self):
        """(float) Sampling frequency."""
        if self._fs is None:
            logging.warning("No sampling frequency has been specified!")
        return self._fs

    @property
    def isempty(self):
        """(bool) checks length of data input"""
        try:
            return self.data.shape[1] == 0
        except IndexError:  # IndexError should happen if _data = []
            return True

    @property
    def n_bytes(self):
        """Approximate number of bytes taken up by object."""
        return utils.PrettyBytes(self.data.nbytes + self._abscissa_vals.nbytes)

    @property
    def n_intervals(self):
        """(int) number of intervals in RegularlySampledAnalogSignalArray"""
        return self._abscissa.support.n_intervals

    @property
    def n_samples(self):
        """(int) number of abscissa samples where signal is defined."""
        if self.isempty:
            return 0
        return utils.PrettyInt(len(self._abscissa_vals))

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

    def __next__(self):
        """AnalogSignal iterator advancer."""
        index = self._index
        if index > self.n_intervals - 1:
            raise StopIteration
        logging.disable(logging.CRITICAL)
        intervalarray = type(self.support)(empty=True)
        exclude = ["_abscissa_vals"]
        attrs = (x for x in self._abscissa.support.__attributes__ if x not in exclude)

        for attr in attrs:
            exec("intervalarray." + attr + " = self._abscissa.support." + attr)
        try:
            intervalarray._data = self._abscissa.support.data[
                tuple([index]), :
            ]  # use np integer indexing! Cool!
        except IndexError:
            # index is out of bounds, so return an empty IntervalArray
            pass
        logging.disable(0)

        self._index += 1

        asa = type(self)([], empty=True)
        exclude = ["_interp", "_support"]
        attrs = (x for x in self.__attributes__ if x not in exclude)
        logging.disable(logging.CRITICAL)
        for attr in attrs:
            exec("asa." + attr + " = self." + attr)
        logging.disable(0)
        asa._restrict_to_interval_array_fast(intervalarray=intervalarray)
        if asa.support.isempty:
            logging.warning(
                "Support is empty. Empty RegularlySampledAnalogSignalArray returned"
            )
            asa = type(self)([], empty=True)

        asa.__renew__()
        return asa

    def empty(self, inplace=True):
        """Remove data (but not metadata) from RegularlySampledAnalogSignalArray.

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

        Note: n_signals is preserved.
        """
        n_signals = self.n_signals
        if not inplace:
            out = self._copy_without_data()
        else:
            out = self
            out._data = np.zeros((n_signals, 0))
        out._abscissa.support = type(self.support)(empty=True)
        out._abscissa_vals = []
        out.__renew__()
        return out

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

        Parameters
        ----------
        idx : IntervalArray, int, slice
            intersect passed intervalarray with support,
            index particular a singular interval or multiple intervals with slice
        """
        intervalslice, signalslice = self._intervalsignalslicer[idx]

        asa = self._subset(signalslice)

        if asa.isempty:
            asa.__renew__()
            return asa

        if isinstance(intervalslice, slice):
            if (
                intervalslice.start is None
                and intervalslice.stop is None
                and intervalslice.step is None
            ):
                asa.__renew__()
                return asa

        newintervals = self._abscissa.support[intervalslice]
        # TODO: this needs to change so that n_signals etc. are preserved
        ################################################################
        if newintervals.isempty:
            logging.warning("Index resulted in empty interval array")
            return self.empty(inplace=False)
        ################################################################

        asa._restrict_to_interval_array_fast(intervalarray=newintervals)
        asa.__renew__()
        return asa

    def _subset(self, idx):
        asa = self.copy()
        try:
            asa._data = np.atleast_2d(self.data[idx, :])
        except IndexError:
            raise IndexError(
                "index {} is out of bounds for n_signals with size {}".format(
                    idx, self.n_signals
                )
            )
        asa.__renew__()
        return asa

    def _copy_without_data(self):
        """Return a copy of self, without data and abscissa_vals.

        Note: the support is left unchanged.
        """
        out = copy.copy(self)  # shallow copy
        out._abscissa_vals = None
        out._data = np.zeros((self.n_signals, 0))
        out = copy.deepcopy(
            out
        )  # just to be on the safe side, but at least now we are not copying the data!
        out.__renew__()
        return out

    def copy(self):
        """Return a copy of the current object."""
        out = copy.deepcopy(self)
        out.__renew__()
        return out

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

    def mean(self, *, axis=1):
        """
        Compute the mean of the data along the specified axis.

        Parameters
        ----------
        axis : int, optional
            Axis along which to compute the mean (default is 1, i.e., across samples).

        Returns
        -------
        mean : np.ndarray
            Mean values along the specified axis.
        """
        try:
            means = np.nanmean(self.data, axis=axis).squeeze()
            if means.size == 1:
                return means.item()
            return means
        except IndexError:
            raise IndexError(
                "Empty RegularlySampledAnalogSignalArray cannot calculate mean"
            )

    def std(self, *, axis=1):
        """
        Compute the standard deviation of the data along the specified axis.

        Parameters
        ----------
        axis : int, optional
            Axis along which to compute the standard deviation (default is 1).

        Returns
        -------
        std : np.ndarray
            Standard deviation values along the specified axis.
        """
        try:
            stds = np.nanstd(self.data, axis=axis).squeeze()
            if stds.size == 1:
                return stds.item()
            return stds
        except IndexError:
            raise IndexError(
                "Empty RegularlySampledAnalogSignalArray cannot calculate standard deviation"
            )

    def max(self, *, axis=1):
        """
        Compute the maximum value of the data along the specified axis.

        Parameters
        ----------
        axis : int, optional
            Axis along which to compute the maximum (default is 1).

        Returns
        -------
        max : np.ndarray
            Maximum values along the specified axis.
        """
        try:
            maxes = np.amax(self.data, axis=axis).squeeze()
            if maxes.size == 1:
                return maxes.item()
            return maxes
        except ValueError:
            raise ValueError(
                "Empty RegularlySampledAnalogSignalArray cannot calculate maximum"
            )

    def min(self, *, axis=1):
        """
        Compute the minimum value of the data along the specified axis.

        Parameters
        ----------
        axis : int, optional
            Axis along which to compute the minimum (default is 1).

        Returns
        -------
        min : np.ndarray
            Minimum values along the specified axis.
        """
        try:
            mins = np.amin(self.data, axis=axis).squeeze()
            if mins.size == 1:
                return mins.item()
            return mins
        except ValueError:
            raise ValueError(
                "Empty RegularlySampledAnalogSignalArray cannot calculate minimum"
            )

    def clip(self, min, max):
        """
        Clip (limit) the values in the data to the interval [min, max].

        Parameters
        ----------
        min : float
            Minimum value.
        max : float
            Maximum value.

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            New object with clipped data.

        Examples
        --------
        >>> clipped = asa.clip(-1, 1)
        """
        out = self.copy()
        out._data = np.clip(self.data, min, max)
        return out

    def trim(self, start, stop=None, *, fs=None):
        """
        Trim the signal to the specified start and stop times.

        Parameters
        ----------
        start : float
            Start time.
        stop : float, optional
            Stop time. If None, trims to the end.
        fs : float, optional
            Sampling frequency. If None, uses self.fs.

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            Trimmed signal array.

        Examples
        --------
        >>> trimmed = asa.trim(0, 10)
        """
        logging.warning("RegularlySampledAnalogSignalArray: Trim may not work!")
        # TODO: do comprehensive input validation
        if stop is not None:
            try:
                start = np.array(start, ndmin=1)
                if len(start) != 1:
                    raise TypeError("start must be a scalar float")
            except TypeError:
                raise TypeError("start must be a scalar float")
            try:
                stop = np.array(stop, ndmin=1)
                if len(stop) != 1:
                    raise TypeError("stop must be a scalar float")
            except TypeError:
                raise TypeError("stop must be a scalar float")
        else:  # start must have two elements
            try:
                if len(np.array(start, ndmin=1)) > 2:
                    raise TypeError(
                        "unsupported input to RegularlySampledAnalogSignalArray.trim()"
                    )
                stop = np.array(start[1], ndmin=1)
                start = np.array(start[0], ndmin=1)
                if len(start) != 1 or len(stop) != 1:
                    raise TypeError("start and stop must be scalar floats")
            except TypeError:
                raise TypeError("start and stop must be scalar floats")

        logging.disable(logging.CRITICAL)
        interval = self._abscissa.support.intersect(
            type(self.support)([start, stop], fs=fs)
        )
        if not interval.isempty:
            analogsignalarray = self[interval]
        else:
            analogsignalarray = type(self)([], empty=True)
        logging.disable(0)
        analogsignalarray.__renew__()
        return analogsignalarray

    @property
    def _ydata_rowsig(self):
        """returns wide-format data s.t. each row is a signal."""
        # LEGACY
        return self.data

    @property
    def _ydata_colsig(self):
        # LEGACY
        """returns skinny-format data s.t. each column is a signal."""
        return self.data.T

    @property
    def _data_rowsig(self):
        """returns wide-format data s.t. each row is a signal."""
        return self.data

    @property
    def _data_colsig(self):
        """returns skinny-format data s.t. each column is a signal."""
        return self.data.T

    def _get_interp1d(
        self,
        *,
        kind="linear",
        copy=True,
        bounds_error=False,
        fill_value=np.nan,
        assume_sorted=None,
    ):
        """returns a scipy interp1d object, extended to have values at all interval
        boundaries!
        """

        if assume_sorted is None:
            assume_sorted = utils.is_sorted(self._abscissa_vals)

        if self.n_signals > 1:
            axis = 1
        else:
            axis = -1

        abscissa_vals = self._abscissa_vals

        if self._ordinate.is_wrapping:
            yvals = self._unwrap(
                self._data_rowsig, self._ordinate.range.min, self._ordinate.range.max
            )  # always interpolate on the unwrapped data!
        else:
            yvals = self._data_rowsig

        lengths = self.lengths
        empty_interval_ids = np.argwhere(lengths == 0).squeeze().tolist()
        first_abscissavals_per_interval_idx = np.insert(np.cumsum(lengths[:-1]), 0, 0)
        first_abscissavals_per_interval_idx[empty_interval_ids] = 0
        last_abscissavals_per_interval_idx = np.cumsum(lengths) - 1
        last_abscissavals_per_interval_idx[empty_interval_ids] = 0
        first_abscissavals_per_interval = self._abscissa_vals[
            first_abscissavals_per_interval_idx
        ]
        last_abscissavals_per_interval = self._abscissa_vals[
            last_abscissavals_per_interval_idx
        ]

        boundary_abscissa_vals = []
        boundary_vals = []
        for ii, (start, stop) in enumerate(self.support.data):
            if lengths[ii] == 0:
                continue
            if first_abscissavals_per_interval[ii] > start:
                boundary_abscissa_vals.append(start)
                boundary_vals.append(yvals[:, first_abscissavals_per_interval_idx[ii]])
                # print('adding {} at abscissa_vals {}'.format(yvals[:,first_abscissavals_per_interval_idx[ii]], start))
            if last_abscissavals_per_interval[ii] < stop:
                boundary_abscissa_vals.append(stop)
                boundary_vals.append(yvals[:, last_abscissavals_per_interval_idx[ii]])

        if boundary_abscissa_vals:
            insert_locs = np.searchsorted(abscissa_vals, boundary_abscissa_vals)
            abscissa_vals = np.insert(
                abscissa_vals, insert_locs, boundary_abscissa_vals
            )
            yvals = np.insert(yvals, insert_locs, np.array(boundary_vals).T, axis=1)

            abscissa_vals, unique_idx = np.unique(abscissa_vals, return_index=True)
            yvals = yvals[:, unique_idx]

        f = interpolate.interp1d(
            x=abscissa_vals,
            y=yvals,
            kind=kind,
            axis=axis,
            copy=copy,
            bounds_error=bounds_error,
            fill_value=fill_value,
            assume_sorted=assume_sorted,
        )
        return f

    def asarray(
        self,
        *,
        where=None,
        at=None,
        kind="linear",
        copy=True,
        bounds_error=False,
        fill_value=np.nan,
        assume_sorted=None,
        recalculate=False,
        store_interp=True,
        n_samples=None,
        split_by_interval=False,
    ):
        """
        Return a data-like array at requested points, with optional interpolation.

        Parameters
        ----------
        where : array_like or tuple, optional
            Array corresponding to np where condition (e.g., where=(data[1,:]>5)).
        at : array_like, optional
            Array of points to evaluate array at. If None, uses self._abscissa_vals.
        n_samples : int, optional
            Number of points to interpolate at, distributed uniformly from support start to stop.
        split_by_interval : bool, optional
            If True, separate arrays by intervals and return in a list.
        kind : str, optional
            Interpolation method. Default is 'linear'.
        copy : bool, optional
            If True, returns a copy. Default is True.
        bounds_error : bool, optional
            If True, raises an error for out-of-bounds interpolation. Default is False.
        fill_value : float, optional
            Value to use for out-of-bounds points. Default is np.nan.
        assume_sorted : bool, optional
            If True, assumes input is sorted. Default is None.
        recalculate : bool, optional
            If True, recalculates the interpolation. Default is False.
        store_interp : bool, optional
            If True, stores the interpolation object. Default is True.

        Returns
        -------
        out : namedtuple (xvals, yvals)
            xvals: array of abscissa values for which data are returned.
            yvals: array of shape (n_signals, n_samples) with interpolated data.

        Examples
        --------
        >>> xvals, yvals = asa.asarray(at=[0, 1, 2])
        """

        # TODO: implement splitting by interval

        if split_by_interval:
            raise NotImplementedError("split_by_interval not yet implemented...")

        XYArray = namedtuple("XYArray", ["xvals", "yvals"])

        if (
            at is None
            and where is None
            and split_by_interval is False
            and n_samples is None
        ):
            xyarray = XYArray(self._abscissa_vals, self._data_rowsig.squeeze())
            return xyarray

        if where is not None:
            assert at is None and n_samples is None, (
                "'where', 'at', and 'n_samples' cannot be used at the same time"
            )
            if isinstance(where, tuple):
                y = np.array(where[1]).squeeze()
                x = where[0]
                assert len(x) == len(y), (
                    "'where' condition and array must have same number of elements"
                )
                at = y[x]
            else:
                x = np.asanyarray(where).squeeze()
                assert len(x) == len(self._abscissa_vals), (
                    "'where' condition must have same number of elements as self._abscissa_vals"
                )
                at = self._abscissa_vals[x]
        elif at is not None:
            assert n_samples is None, (
                "'at' and 'n_samples' cannot be used at the same time"
            )
        else:
            at = np.linspace(self.support.start, self.support.stop, n_samples)

        at = np.atleast_1d(at)
        if at.ndim > 1:
            raise ValueError("Requested points must be one-dimensional!")
        if at.shape[0] == 0:
            raise ValueError("No points were requested to interpolate")

        # if we made it this far, either at or where has been specified, and at is now well defined.

        kwargs = {
            "kind": kind,
            "copy": copy,
            "bounds_error": bounds_error,
            "fill_value": fill_value,
            "assume_sorted": assume_sorted,
        }

        # retrieve an existing, or construct a new interpolation object
        if recalculate:
            interpobj = self._get_interp1d(**kwargs)
        else:
            try:
                interpobj = self._interp
                if interpobj is None:
                    interpobj = self._get_interp1d(**kwargs)
            except AttributeError:  # does not exist yet
                interpobj = self._get_interp1d(**kwargs)

        # store interpolation object, if desired
        if store_interp:
            self._interp = interpobj

        # do not interpolate points that lie outside the support
        interval_data = self.support.data[:, :, None]
        # use broadcasting to check in a vectorized manner if
        # each sample falls within the support, haha aren't we clever?
        # (n_intervals, n_requested_samples)
        valid = np.logical_and(
            at >= interval_data[:, 0, :], at <= interval_data[:, 1, :]
        )
        valid_mask = np.any(valid, axis=0)
        n_invalid = at.size - np.sum(valid_mask)
        if n_invalid > 0:
            logging.warning(
                "{} values outside the support were removed".format(n_invalid)
            )
        at = at[valid_mask]

        # do the actual interpolation
        if self._ordinate.is_wrapping:
            try:
                if self.is_wrapped:
                    out = self._wrap(
                        interpobj(at),
                        self._ordinate.range.min,
                        self._ordinate.range.max,
                    )
                else:
                    out = interpobj(at)
            except SystemError:
                interpobj = self._get_interp1d(**kwargs)
                if store_interp:
                    self._interp = interpobj
                if self.is_wrapped:
                    out = self._wrap(
                        interpobj(at),
                        self._ordinate.range.min,
                        self._ordinate.range.max,
                    )
                else:
                    out = interpobj(at)
        else:
            try:
                out = interpobj(at)
            except SystemError:
                interpobj = self._get_interp1d(**kwargs)
                if store_interp:
                    self._interp = interpobj
                out = interpobj(at)

        xyarray = XYArray(xvals=np.asanyarray(at), yvals=np.asanyarray(out))
        return xyarray

    def subsample(self, *, fs):
        """Subsamples a RegularlySampledAnalogSignalArray

        WARNING! Aliasing can occur! It is better to use downsample when
        lowering the sampling rate substantially.

        Parameters
        ----------
        fs : float, optional
            Desired output sampling rate, in Hz

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            Copy of RegularlySampledAnalogSignalArray where data is only stored at the
            new subset of points.
        """

        return self.simplify(ds=1 / fs)

    def simplify(self, *, ds=None, n_samples=None, **kwargs):
        """Returns an RegularlySampledAnalogSignalArray where the data has been
        simplified / subsampled.

        This function is primarily intended to be used for plotting and
        saving vector graphics without having too large file sizes as
        a result of too many points.

        Irrespective of whether 'ds' or 'n_samples' 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_samples or ds to be violated.

        WARNING! Simplify can create nan samples, when requesting a timestamp
        within an interval, but outside of the (first, last) abscissa_vals within that
        interval, since we don't extrapolate, but only interpolate. # TODO: fix

        Parameters
        ----------
        ds : float, optional
            Time (in seconds), in which to step points.
        n_samples : int, optional
            Number of points at which to intepolate data. If ds is None
            and n_samples is None, then default is to use n_samples=5,000

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            Copy of RegularlySampledAnalogSignalArray where data is only stored at the
            new subset of points.
        """

        if self.isempty:
            return self

        # legacy kwarg support:
        n_points = kwargs.pop("n_points", False)
        if n_points:
            n_samples = n_points

        if ds is not None and n_samples is not None:
            raise ValueError("ds and n_samples cannot be used together")

        if n_samples is not None:
            assert float(n_samples).is_integer(), (
                "n_samples must be a positive integer!"
            )
            assert n_samples > 1, "n_samples must be a positive integer > 1"
            # determine ds from number of desired points:
            ds = self.support.length / (n_samples - 1)

        if ds is None:
            # neither n_samples nor ds was specified, so assume defaults:
            n_samples = np.min((5000, 250 + self.n_samples // 2, self.n_samples))
            ds = self.support.length / (n_samples - 1)

        # build list of points at which to evaluate the RegularlySampledAnalogSignalArray

        # we exclude all empty intervals:
        at = []
        lengths = self.lengths
        empty_interval_ids = np.argwhere(lengths == 0).squeeze().tolist()
        first_abscissavals_per_interval_idx = np.insert(np.cumsum(lengths[:-1]), 0, 0)
        first_abscissavals_per_interval_idx[empty_interval_ids] = 0
        last_abscissavals_per_interval_idx = np.cumsum(lengths) - 1
        last_abscissavals_per_interval_idx[empty_interval_ids] = 0
        first_abscissavals_per_interval = self._abscissa_vals[
            first_abscissavals_per_interval_idx
        ]
        last_abscissavals_per_interval = self._abscissa_vals[
            last_abscissavals_per_interval_idx
        ]

        for ii, (start, stop) in enumerate(self.support.data):
            if lengths[ii] == 0:
                continue
            newxvals = utils.frange(
                first_abscissavals_per_interval[ii],
                last_abscissavals_per_interval[ii],
                step=ds,
            ).tolist()
            at.extend(newxvals)
            try:
                if newxvals[-1] < last_abscissavals_per_interval[ii]:
                    at.append(last_abscissavals_per_interval[ii])
            except IndexError:
                at.append(first_abscissavals_per_interval[ii])
                at.append(last_abscissavals_per_interval[ii])

        _, yvals = self.asarray(at=at, recalculate=True, store_interp=False)
        yvals = np.array(yvals, ndmin=2)

        asa = self.copy()
        asa._abscissa_vals = np.asanyarray(at)
        asa._data = yvals
        asa._fs = 1 / ds

        return asa

    def join(self, other, *, mode=None, inplace=False):
        """Join another RegularlySampledAnalogSignalArray to this one.

        WARNING! Numerical precision might cause some epochs to be considered
        non-disjoint even when they really are, so a better check than ep1[ep2].isempty
        is to check for samples contained in the intersection of ep1 and ep2.

        Parameters
        ----------
        other : RegularlySampledAnalogSignalArray
            RegularlySampledAnalogSignalArray (or derived type) to join to the current
            RegularlySampledAnalogSignalArray. Other must have the same number of signals as
            the current RegularlySampledAnalogSignalArray.
        mode : string, optional
            One of ['max', 'min', 'left', 'right', 'mean']. Specifies how the
            signals are merged inside overlapping intervals. Default is 'left'.
        inplace : boolean, optional
            If True, then current RegularlySampledAnalogSignalArray is modified. If False, then
            a copy with the joined result is returned. Default is False.

        Returns
        -------
        out : RegularlySampledAnalogSignalArray
            Copy of RegularlySampledAnalogSignalArray where the new RegularlySampledAnalogSignalArray has been
            joined to the current RegularlySampledAnalogSignalArray.
        """

        if mode is None:
            mode = "left"

        asa = self.copy()  # copy without data since we change data at the end?

        times = np.zeros((1, 0))
        data = np.zeros((asa.n_signals, 0))

        # if ASAs are disjoint:
        if not self.support[other.support].length > 50 * float_info.epsilon:
            # do a simple-as-butter join (concat) and sort
            times = np.append(times, self._abscissa_vals)
            data = np.hstack((data, self.data))
            times = np.append(times, other._abscissa_vals)
            data = np.hstack((data, other.data))
        else:  # not disjoint
            both_eps = self.support[other.support]
            self_eps = self.support - both_eps - other.support
            other_eps = other.support - both_eps - self.support

            if mode == "left":
                self_eps += both_eps
                # print(self_eps)

                tmp = self[self_eps]
                times = np.append(times, tmp._abscissa_vals)
                data = np.hstack((data, tmp.data))

                if not other_eps.isempty:
                    tmp = other[other_eps]
                    times = np.append(times, tmp._abscissa_vals)
                    data = np.hstack((data, tmp.data))
            elif mode == "right":
                other_eps += both_eps

                tmp = other[other_eps]
                times = np.append(times, tmp._abscissa_vals)
                data = np.hstack((data, tmp.data))

                if not self_eps.isempty:
                    tmp = self[self_eps]
                    times = np.append(times, tmp._abscissa_vals)
                    data = np.hstack((data, tmp.data))
            else:
                raise NotImplementedError(
                    "asa.join() has not yet been implemented for mode '{}'!".format(
                        mode
                    )
                )

        sample_order = np.argsort(times)
        times = times[sample_order]
        data = data[:, sample_order]

        asa._data = data
        asa._abscissa_vals = times
        dom1 = self.domain
        dom2 = other.domain
        asa._abscissa.support = (self.support + other.support).merge()
        asa._abscissa.support.domain = (dom1 + dom2).merge()
        return asa

    def _pdf(self, bins=None, n_samples=None):
        """Return the probability distribution function for each signal."""
        from scipy import integrate

        if bins is None:
            bins = 100

        if n_samples is None:
            n_samples = 100

        if self.n_signals > 1:
            raise NotImplementedError("multiple signals not supported yet!")

        # fx, bins = np.histogram(self.data.squeeze(), bins=bins, normed=True)
        fx, bins = np.histogram(self.data.squeeze(), bins=bins)
        bin_centers = (bins + (bins[1] - bins[0]) / 2)[:-1]

        Ifx = integrate.simps(fx, bin_centers)

        pdf = type(self)(
            abscissa_vals=bin_centers,
            data=fx / Ifx,
            fs=1 / (bin_centers[1] - bin_centers[0]),
            support=type(self.support)(self.data.min(), self.data.max()),
        ).simplify(n_samples=n_samples)

        return pdf

        # data = []
        # for signal in self.data:
        #     fx, bins = np.histogram(signal, bins=bins)
        #     bin_centers = (bins + (bins[1]-bins[0])/2)[:-1]

    def _cdf(self, n_samples=None):
        """Return the probability distribution function for each signal."""

        if n_samples is None:
            n_samples = 100

        if self.n_signals > 1:
            raise NotImplementedError("multiple signals not supported yet!")

        X = np.sort(self.data.squeeze())
        F = np.array(range(self.n_samples)) / float(self.n_samples)

        logging.disable(logging.CRITICAL)
        cdf = type(self)(
            abscissa_vals=X,
            data=F,
            support=type(self.support)(self.data.min(), self.data.max()),
        ).simplify(n_samples=n_samples)
        logging.disable(0)

        return cdf

    def _eegplot(self, ax=None, normalize=False, pad=None, fill=True, color=None):
        """custom_func docstring goes here."""

        import matplotlib.pyplot as plt

        from ..plotting import utils as plotutils

        if ax is None:
            ax = plt.gca()

        xmin = self.support.min
        xmax = self.support.max
        xvals = self._abscissa_vals

        if pad is None:
            pad = np.mean(self.data) / 2

        data = self.data.copy()

        if normalize:
            peak_vals = self.max()
            data = (data.T / peak_vals).T

        n_traces = self.n_signals

        for tt, trace in enumerate(data):
            if color is None:
                line = ax.plot(
                    xvals, tt * pad + trace, zorder=int(10 + 2 * n_traces - 2 * tt)
                )
            else:
                line = ax.plot(
                    xvals,
                    tt * pad + trace,
                    zorder=int(10 + 2 * n_traces - 2 * tt),
                    color=color,
                )
            if fill:
                # Get the color from the current curve
                fillcolor = line[0].get_color()
                ax.fill_between(
                    xvals,
                    tt * pad,
                    tt * pad + trace,
                    alpha=0.3,
                    color=fillcolor,
                    zorder=int(10 + 2 * n_traces - 2 * tt - 1),
                )

        ax.set_xlim(xmin, xmax)
        if pad != 0:
            # yticks = np.arange(n_traces)*pad + 0.5*pad
            yticks = []
            ax.set_yticks(yticks)
            ax.set_xlabel(self._abscissa.label)
            ax.set_ylabel(self._ordinate.label)
            plotutils.no_yticks(ax)
            plotutils.clear_left(ax)

        plotutils.clear_top(ax)
        plotutils.clear_right(ax)

        return ax

    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)

abs property

RegularlySampledAnalogSignalArray with absolute value of (potentially complex) data.

abscissa_vals property writable

(np.array 1D) Time in seconds.

angle property

RegularlySampledAnalogSignalArray with only phase angle (in radians) of data.

base_unit property

Base unit of the abscissa.

data property writable

(np.array N-Dimensional) data with shape (n_signals, n_samples).

domain property writable

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

fs property

(float) Sampling frequency.

imag property

RegularlySampledAnalogSignalArray with only imaginary part of data.

iscomplex property

Returns True if any part of the signal is complex.

isempty property

(bool) checks length of data input

isreal property

Returns True if entire signal is real.

labels property

(list) The labels corresponding to each signal.

lengths property

(list) The number of samples in each interval.

n_bytes property

Approximate number of bytes taken up by object.

n_intervals property

(int) number of intervals in RegularlySampledAnalogSignalArray

n_samples property

(int) number of abscissa samples where signal is defined.

n_signals property

(int) The number of signals.

range property writable

(nelpy.IntervalArray) The range of the underlying RegularlySampledAnalogSignalArray.

real property

RegularlySampledAnalogSignalArray with only real part of data.

signals property

Returns a list of RegularlySampledAnalogSignalArrays, each array containing a single signal (channel).

WARNING: this method creates a copy of each signal, so is not particularly efficient at this time.

Examples:

>>> for channel in lfp.signals:
    print(channel)

step property

steps per sample Example 1: sample_numbers = np.array([1,2,3,4,5,6]) #aka time Steps per sample in the above case would be 1

Example 2: sample_numbers = np.array([1,3,5,7,9]) #aka time Steps per sample in Example 2 would be 2

support property writable

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

add_signal(signal, label=None)

Docstring goes here. Basically we add a signal, and we add a label. THIS HAPPENS IN PLACE?

Source code in nelpy/core/_analogsignalarray.py
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
def add_signal(self, signal, label=None):
    """Docstring goes here.
    Basically we add a signal, and we add a label. THIS HAPPENS IN PLACE?
    """
    # TODO: add functionality to check that supports are the same, etc.
    if isinstance(signal, RegularlySampledAnalogSignalArray):
        signal = signal.data

    signal = np.squeeze(signal)
    if signal.ndim > 1:
        raise TypeError("Can only add one signal at a time!")
    if self.data.ndim == 1:
        self._data = np.vstack(
            [np.array(self.data, ndmin=2), np.array(signal, ndmin=2)]
        )
    else:
        self._data = np.vstack([self.data, np.array(signal, ndmin=2)])
    if label is None:
        logging.warning("None label appended")
    self._labels = np.append(self._labels, label)
    return self

asarray(*, where=None, at=None, kind='linear', copy=True, bounds_error=False, fill_value=np.nan, assume_sorted=None, recalculate=False, store_interp=True, n_samples=None, split_by_interval=False)

Return a data-like array at requested points, with optional interpolation.

Parameters:

Name Type Description Default
where array_like or tuple

Array corresponding to np where condition (e.g., where=(data[1,:]>5)).

None
at array_like

Array of points to evaluate array at. If None, uses self._abscissa_vals.

None
n_samples int

Number of points to interpolate at, distributed uniformly from support start to stop.

None
split_by_interval bool

If True, separate arrays by intervals and return in a list.

False
kind str

Interpolation method. Default is 'linear'.

'linear'
copy bool

If True, returns a copy. Default is True.

True
bounds_error bool

If True, raises an error for out-of-bounds interpolation. Default is False.

False
fill_value float

Value to use for out-of-bounds points. Default is np.nan.

nan
assume_sorted bool

If True, assumes input is sorted. Default is None.

None
recalculate bool

If True, recalculates the interpolation. Default is False.

False
store_interp bool

If True, stores the interpolation object. Default is True.

True

Returns:

Name Type Description
out namedtuple(xvals, yvals)

xvals: array of abscissa values for which data are returned. yvals: array of shape (n_signals, n_samples) with interpolated data.

Examples:

>>> xvals, yvals = asa.asarray(at=[0, 1, 2])
Source code in nelpy/core/_analogsignalarray.py
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
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
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
def asarray(
    self,
    *,
    where=None,
    at=None,
    kind="linear",
    copy=True,
    bounds_error=False,
    fill_value=np.nan,
    assume_sorted=None,
    recalculate=False,
    store_interp=True,
    n_samples=None,
    split_by_interval=False,
):
    """
    Return a data-like array at requested points, with optional interpolation.

    Parameters
    ----------
    where : array_like or tuple, optional
        Array corresponding to np where condition (e.g., where=(data[1,:]>5)).
    at : array_like, optional
        Array of points to evaluate array at. If None, uses self._abscissa_vals.
    n_samples : int, optional
        Number of points to interpolate at, distributed uniformly from support start to stop.
    split_by_interval : bool, optional
        If True, separate arrays by intervals and return in a list.
    kind : str, optional
        Interpolation method. Default is 'linear'.
    copy : bool, optional
        If True, returns a copy. Default is True.
    bounds_error : bool, optional
        If True, raises an error for out-of-bounds interpolation. Default is False.
    fill_value : float, optional
        Value to use for out-of-bounds points. Default is np.nan.
    assume_sorted : bool, optional
        If True, assumes input is sorted. Default is None.
    recalculate : bool, optional
        If True, recalculates the interpolation. Default is False.
    store_interp : bool, optional
        If True, stores the interpolation object. Default is True.

    Returns
    -------
    out : namedtuple (xvals, yvals)
        xvals: array of abscissa values for which data are returned.
        yvals: array of shape (n_signals, n_samples) with interpolated data.

    Examples
    --------
    >>> xvals, yvals = asa.asarray(at=[0, 1, 2])
    """

    # TODO: implement splitting by interval

    if split_by_interval:
        raise NotImplementedError("split_by_interval not yet implemented...")

    XYArray = namedtuple("XYArray", ["xvals", "yvals"])

    if (
        at is None
        and where is None
        and split_by_interval is False
        and n_samples is None
    ):
        xyarray = XYArray(self._abscissa_vals, self._data_rowsig.squeeze())
        return xyarray

    if where is not None:
        assert at is None and n_samples is None, (
            "'where', 'at', and 'n_samples' cannot be used at the same time"
        )
        if isinstance(where, tuple):
            y = np.array(where[1]).squeeze()
            x = where[0]
            assert len(x) == len(y), (
                "'where' condition and array must have same number of elements"
            )
            at = y[x]
        else:
            x = np.asanyarray(where).squeeze()
            assert len(x) == len(self._abscissa_vals), (
                "'where' condition must have same number of elements as self._abscissa_vals"
            )
            at = self._abscissa_vals[x]
    elif at is not None:
        assert n_samples is None, (
            "'at' and 'n_samples' cannot be used at the same time"
        )
    else:
        at = np.linspace(self.support.start, self.support.stop, n_samples)

    at = np.atleast_1d(at)
    if at.ndim > 1:
        raise ValueError("Requested points must be one-dimensional!")
    if at.shape[0] == 0:
        raise ValueError("No points were requested to interpolate")

    # if we made it this far, either at or where has been specified, and at is now well defined.

    kwargs = {
        "kind": kind,
        "copy": copy,
        "bounds_error": bounds_error,
        "fill_value": fill_value,
        "assume_sorted": assume_sorted,
    }

    # retrieve an existing, or construct a new interpolation object
    if recalculate:
        interpobj = self._get_interp1d(**kwargs)
    else:
        try:
            interpobj = self._interp
            if interpobj is None:
                interpobj = self._get_interp1d(**kwargs)
        except AttributeError:  # does not exist yet
            interpobj = self._get_interp1d(**kwargs)

    # store interpolation object, if desired
    if store_interp:
        self._interp = interpobj

    # do not interpolate points that lie outside the support
    interval_data = self.support.data[:, :, None]
    # use broadcasting to check in a vectorized manner if
    # each sample falls within the support, haha aren't we clever?
    # (n_intervals, n_requested_samples)
    valid = np.logical_and(
        at >= interval_data[:, 0, :], at <= interval_data[:, 1, :]
    )
    valid_mask = np.any(valid, axis=0)
    n_invalid = at.size - np.sum(valid_mask)
    if n_invalid > 0:
        logging.warning(
            "{} values outside the support were removed".format(n_invalid)
        )
    at = at[valid_mask]

    # do the actual interpolation
    if self._ordinate.is_wrapping:
        try:
            if self.is_wrapped:
                out = self._wrap(
                    interpobj(at),
                    self._ordinate.range.min,
                    self._ordinate.range.max,
                )
            else:
                out = interpobj(at)
        except SystemError:
            interpobj = self._get_interp1d(**kwargs)
            if store_interp:
                self._interp = interpobj
            if self.is_wrapped:
                out = self._wrap(
                    interpobj(at),
                    self._ordinate.range.min,
                    self._ordinate.range.max,
                )
            else:
                out = interpobj(at)
    else:
        try:
            out = interpobj(at)
        except SystemError:
            interpobj = self._get_interp1d(**kwargs)
            if store_interp:
                self._interp = interpobj
            out = interpobj(at)

    xyarray = XYArray(xvals=np.asanyarray(at), yvals=np.asanyarray(out))
    return xyarray

center(inplace=False)

Center the data to have zero mean along the sample axis.

Parameters:

Name Type Description Default
inplace bool

If True, modifies the data in place. If False (default), returns a new object.

False

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

The centered signal array.

Examples:

>>> centered = asa.center()
>>> centered.mean()
0.0
Source code in nelpy/core/_analogsignalarray.py
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
def center(self, inplace=False):
    """
    Center the data to have zero mean along the sample axis.

    Parameters
    ----------
    inplace : bool, optional
        If True, modifies the data in place. If False (default), returns a new object.

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        The centered signal array.

    Examples
    --------
    >>> centered = asa.center()
    >>> centered.mean()
    0.0
    """
    if inplace:
        out = self
    else:
        out = self.copy()
    out._data = (out._data.T - out.mean()).T
    return out

clip(min, max)

Clip (limit) the values in the data to the interval [min, max].

Parameters:

Name Type Description Default
min float

Minimum value.

required
max float

Maximum value.

required

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

New object with clipped data.

Examples:

>>> clipped = asa.clip(-1, 1)
Source code in nelpy/core/_analogsignalarray.py
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
def clip(self, min, max):
    """
    Clip (limit) the values in the data to the interval [min, max].

    Parameters
    ----------
    min : float
        Minimum value.
    max : float
        Maximum value.

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        New object with clipped data.

    Examples
    --------
    >>> clipped = asa.clip(-1, 1)
    """
    out = self.copy()
    out._data = np.clip(self.data, min, max)
    return out

copy()

Return a copy of the current object.

Source code in nelpy/core/_analogsignalarray.py
1873
1874
1875
1876
1877
def copy(self):
    """Return a copy of the current object."""
    out = copy.deepcopy(self)
    out.__renew__()
    return out

ddt(rectify=False)

Returns the derivative of each signal in the RegularlySampledAnalogSignalArray.

asa.data = f(t) asa.ddt = d/dt (asa.data)

Parameters:

Name Type Description Default
rectify boolean

If True, the absolute value of the derivative will be returned. Default is False.

False

Returns:

Name Type Description
ddt RegularlySampledAnalogSignalArray

Time derivative of each signal in the RegularlySampledAnalogSignalArray.

Note

Second order central differences are used here, and it is assumed that the signals are sampled uniformly. If the signals are not uniformly sampled, it is recommended to resample the signal before computing the derivative.

Source code in nelpy/core/_analogsignalarray.py
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
def ddt(self, rectify=False):
    """Returns the derivative of each signal in the RegularlySampledAnalogSignalArray.

    asa.data = f(t)
    asa.ddt = d/dt (asa.data)

    Parameters
    ----------
    rectify : boolean, optional
        If True, the absolute value of the derivative will be returned.
        Default is False.

    Returns
    -------
    ddt : RegularlySampledAnalogSignalArray
        Time derivative of each signal in the RegularlySampledAnalogSignalArray.

    Note
    ----
    Second order central differences are used here, and it is assumed that
    the signals are sampled uniformly. If the signals are not uniformly
    sampled, it is recommended to resample the signal before computing the
    derivative.
    """
    ddt = utils.ddt_asa(self, rectify=rectify)
    return ddt

downsample(*, fs_out, aafilter=True, inplace=False, **kwargs)

Downsamples the RegularlySampledAnalogSignalArray

Parameters:

Name Type Description Default
fs_out float

Desired output sampling rate in Hz

required
aafilter boolean

Whether to apply an anti-aliasing filter before performing the actual downsampling. Default is True

True
inplace boolean

If True, the output ASA will replace the input ASA. Default is False

False
kwargs

Other keyword arguments are passed to sosfiltfilt() in the filtering module

{}

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

The downsampled RegularlySampledAnalogSignalArray

Source code in nelpy/core/_analogsignalarray.py
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
def downsample(self, *, fs_out, aafilter=True, inplace=False, **kwargs):
    """Downsamples the RegularlySampledAnalogSignalArray

    Parameters
    ----------
    fs_out : float, optional
        Desired output sampling rate in Hz
    aafilter : boolean, optional
        Whether to apply an anti-aliasing filter before performing the actual
        downsampling. Default is True
    inplace : boolean, optional
        If True, the output ASA will replace the input ASA. Default is False
    kwargs :
        Other keyword arguments are passed to sosfiltfilt() in the `filtering`
        module

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        The downsampled RegularlySampledAnalogSignalArray
    """

    if not fs_out < self._fs:
        raise ValueError("fs_out must be less than current sampling rate!")

    if aafilter:
        fh = fs_out / 2.0
        out = filtering.sosfiltfilt(self, fl=None, fh=fh, inplace=inplace, **kwargs)

    downsampled = out.simplify(ds=1 / fs_out)
    out._data = downsampled._data
    out._abscissa_vals = downsampled._abscissa_vals
    out._fs = fs_out

    out.__renew__()
    return out

empty(inplace=True)

Remove data (but not metadata) from RegularlySampledAnalogSignalArray.

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

Note: n_signals is preserved.

Source code in nelpy/core/_analogsignalarray.py
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
def empty(self, inplace=True):
    """Remove data (but not metadata) from RegularlySampledAnalogSignalArray.

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

    Note: n_signals is preserved.
    """
    n_signals = self.n_signals
    if not inplace:
        out = self._copy_without_data()
    else:
        out = self
        out._data = np.zeros((n_signals, 0))
    out._abscissa.support = type(self.support)(empty=True)
    out._abscissa_vals = []
    out.__renew__()
    return out

join(other, *, mode=None, inplace=False)

Join another RegularlySampledAnalogSignalArray to this one.

WARNING! Numerical precision might cause some epochs to be considered non-disjoint even when they really are, so a better check than ep1[ep2].isempty is to check for samples contained in the intersection of ep1 and ep2.

Parameters:

Name Type Description Default
other RegularlySampledAnalogSignalArray

RegularlySampledAnalogSignalArray (or derived type) to join to the current RegularlySampledAnalogSignalArray. Other must have the same number of signals as the current RegularlySampledAnalogSignalArray.

required
mode string

One of ['max', 'min', 'left', 'right', 'mean']. Specifies how the signals are merged inside overlapping intervals. Default is 'left'.

None
inplace boolean

If True, then current RegularlySampledAnalogSignalArray is modified. If False, then a copy with the joined result is returned. Default is False.

False

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

Copy of RegularlySampledAnalogSignalArray where the new RegularlySampledAnalogSignalArray has been joined to the current RegularlySampledAnalogSignalArray.

Source code in nelpy/core/_analogsignalarray.py
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
def join(self, other, *, mode=None, inplace=False):
    """Join another RegularlySampledAnalogSignalArray to this one.

    WARNING! Numerical precision might cause some epochs to be considered
    non-disjoint even when they really are, so a better check than ep1[ep2].isempty
    is to check for samples contained in the intersection of ep1 and ep2.

    Parameters
    ----------
    other : RegularlySampledAnalogSignalArray
        RegularlySampledAnalogSignalArray (or derived type) to join to the current
        RegularlySampledAnalogSignalArray. Other must have the same number of signals as
        the current RegularlySampledAnalogSignalArray.
    mode : string, optional
        One of ['max', 'min', 'left', 'right', 'mean']. Specifies how the
        signals are merged inside overlapping intervals. Default is 'left'.
    inplace : boolean, optional
        If True, then current RegularlySampledAnalogSignalArray is modified. If False, then
        a copy with the joined result is returned. Default is False.

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        Copy of RegularlySampledAnalogSignalArray where the new RegularlySampledAnalogSignalArray has been
        joined to the current RegularlySampledAnalogSignalArray.
    """

    if mode is None:
        mode = "left"

    asa = self.copy()  # copy without data since we change data at the end?

    times = np.zeros((1, 0))
    data = np.zeros((asa.n_signals, 0))

    # if ASAs are disjoint:
    if not self.support[other.support].length > 50 * float_info.epsilon:
        # do a simple-as-butter join (concat) and sort
        times = np.append(times, self._abscissa_vals)
        data = np.hstack((data, self.data))
        times = np.append(times, other._abscissa_vals)
        data = np.hstack((data, other.data))
    else:  # not disjoint
        both_eps = self.support[other.support]
        self_eps = self.support - both_eps - other.support
        other_eps = other.support - both_eps - self.support

        if mode == "left":
            self_eps += both_eps
            # print(self_eps)

            tmp = self[self_eps]
            times = np.append(times, tmp._abscissa_vals)
            data = np.hstack((data, tmp.data))

            if not other_eps.isempty:
                tmp = other[other_eps]
                times = np.append(times, tmp._abscissa_vals)
                data = np.hstack((data, tmp.data))
        elif mode == "right":
            other_eps += both_eps

            tmp = other[other_eps]
            times = np.append(times, tmp._abscissa_vals)
            data = np.hstack((data, tmp.data))

            if not self_eps.isempty:
                tmp = self[self_eps]
                times = np.append(times, tmp._abscissa_vals)
                data = np.hstack((data, tmp.data))
        else:
            raise NotImplementedError(
                "asa.join() has not yet been implemented for mode '{}'!".format(
                    mode
                )
            )

    sample_order = np.argsort(times)
    times = times[sample_order]
    data = data[:, sample_order]

    asa._data = data
    asa._abscissa_vals = times
    dom1 = self.domain
    dom2 = other.domain
    asa._abscissa.support = (self.support + other.support).merge()
    asa._abscissa.support.domain = (dom1 + dom2).merge()
    return asa

max(*, axis=1)

Compute the maximum value of the data along the specified axis.

Parameters:

Name Type Description Default
axis int

Axis along which to compute the maximum (default is 1).

1

Returns:

Name Type Description
max ndarray

Maximum values along the specified axis.

Source code in nelpy/core/_analogsignalarray.py
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
def max(self, *, axis=1):
    """
    Compute the maximum value of the data along the specified axis.

    Parameters
    ----------
    axis : int, optional
        Axis along which to compute the maximum (default is 1).

    Returns
    -------
    max : np.ndarray
        Maximum values along the specified axis.
    """
    try:
        maxes = np.amax(self.data, axis=axis).squeeze()
        if maxes.size == 1:
            return maxes.item()
        return maxes
    except ValueError:
        raise ValueError(
            "Empty RegularlySampledAnalogSignalArray cannot calculate maximum"
        )

mean(*, axis=1)

Compute the mean of the data along the specified axis.

Parameters:

Name Type Description Default
axis int

Axis along which to compute the mean (default is 1, i.e., across samples).

1

Returns:

Name Type Description
mean ndarray

Mean values along the specified axis.

Source code in nelpy/core/_analogsignalarray.py
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
def mean(self, *, axis=1):
    """
    Compute the mean of the data along the specified axis.

    Parameters
    ----------
    axis : int, optional
        Axis along which to compute the mean (default is 1, i.e., across samples).

    Returns
    -------
    mean : np.ndarray
        Mean values along the specified axis.
    """
    try:
        means = np.nanmean(self.data, axis=axis).squeeze()
        if means.size == 1:
            return means.item()
        return means
    except IndexError:
        raise IndexError(
            "Empty RegularlySampledAnalogSignalArray cannot calculate mean"
        )

median(*, axis=1)

Returns the median of each signal in RegularlySampledAnalogSignalArray.

Source code in nelpy/core/_analogsignalarray.py
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
def median(self, *, axis=1):
    """Returns the median of each signal in RegularlySampledAnalogSignalArray."""
    try:
        medians = np.nanmedian(self.data, axis=axis).squeeze()
        if medians.size == 1:
            return medians.item()
        return medians
    except IndexError:
        raise IndexError(
            "Empty RegularlySampledAnalogSignalArray cannot calculate median"
        )

min(*, axis=1)

Compute the minimum value of the data along the specified axis.

Parameters:

Name Type Description Default
axis int

Axis along which to compute the minimum (default is 1).

1

Returns:

Name Type Description
min ndarray

Minimum values along the specified axis.

Source code in nelpy/core/_analogsignalarray.py
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
def min(self, *, axis=1):
    """
    Compute the minimum value of the data along the specified axis.

    Parameters
    ----------
    axis : int, optional
        Axis along which to compute the minimum (default is 1).

    Returns
    -------
    min : np.ndarray
        Minimum values along the specified axis.
    """
    try:
        mins = np.amin(self.data, axis=axis).squeeze()
        if mins.size == 1:
            return mins.item()
        return mins
    except ValueError:
        raise ValueError(
            "Empty RegularlySampledAnalogSignalArray cannot calculate minimum"
        )

normalize(inplace=False)

Normalize the data to have unit standard deviation along the sample axis.

Parameters:

Name Type Description Default
inplace bool

If True, modifies the data in place. If False (default), returns a new object.

False

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

The normalized signal array.

Examples:

>>> normalized = asa.normalize()
>>> normalized.std()
1.0
Source code in nelpy/core/_analogsignalarray.py
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
def normalize(self, inplace=False):
    """
    Normalize the data to have unit standard deviation along the sample axis.

    Parameters
    ----------
    inplace : bool, optional
        If True, modifies the data in place. If False (default), returns a new object.

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        The normalized signal array.

    Examples
    --------
    >>> normalized = asa.normalize()
    >>> normalized.std()
    1.0
    """
    if inplace:
        out = self
    else:
        out = self.copy()
    std = np.atleast_1d(out.std())
    std[std == 0] = 1
    out._data = (out._data.T / std).T
    return out

partition(ds=None, n_intervals=None)

Returns an RegularlySampledAnalogSignalArray whose support has been partitioned.

Parameters:

Name Type Description Default
ds float

Maximum duration (in seconds), for each interval.

None
n_samples 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 RegularlySampledAnalogSignalArray

RegularlySampledAnalogSignalArray 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_samples or ds to be violated.

Source code in nelpy/core/_analogsignalarray.py
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
@keyword_equivalence(this_or_that={"n_intervals": "n_epochs"})
def partition(self, ds=None, n_intervals=None):
    """Returns an RegularlySampledAnalogSignalArray whose support has been
    partitioned.

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

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        RegularlySampledAnalogSignalArray 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_samples or ds to be violated.
    """

    out = self.copy()
    out._abscissa.support = out.support.partition(ds=ds, n_intervals=n_intervals)
    return out

simplify(*, ds=None, n_samples=None, **kwargs)

Returns an RegularlySampledAnalogSignalArray where the data has been simplified / subsampled.

This function is primarily intended to be used for plotting and saving vector graphics without having too large file sizes as a result of too many points.

Irrespective of whether 'ds' or 'n_samples' 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_samples or ds to be violated.

WARNING! Simplify can create nan samples, when requesting a timestamp within an interval, but outside of the (first, last) abscissa_vals within that interval, since we don't extrapolate, but only interpolate. # TODO: fix

Parameters:

Name Type Description Default
ds float

Time (in seconds), in which to step points.

None
n_samples int

Number of points at which to intepolate data. If ds is None and n_samples is None, then default is to use n_samples=5,000

None

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

Copy of RegularlySampledAnalogSignalArray where data is only stored at the new subset of points.

Source code in nelpy/core/_analogsignalarray.py
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
def simplify(self, *, ds=None, n_samples=None, **kwargs):
    """Returns an RegularlySampledAnalogSignalArray where the data has been
    simplified / subsampled.

    This function is primarily intended to be used for plotting and
    saving vector graphics without having too large file sizes as
    a result of too many points.

    Irrespective of whether 'ds' or 'n_samples' 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_samples or ds to be violated.

    WARNING! Simplify can create nan samples, when requesting a timestamp
    within an interval, but outside of the (first, last) abscissa_vals within that
    interval, since we don't extrapolate, but only interpolate. # TODO: fix

    Parameters
    ----------
    ds : float, optional
        Time (in seconds), in which to step points.
    n_samples : int, optional
        Number of points at which to intepolate data. If ds is None
        and n_samples is None, then default is to use n_samples=5,000

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        Copy of RegularlySampledAnalogSignalArray where data is only stored at the
        new subset of points.
    """

    if self.isempty:
        return self

    # legacy kwarg support:
    n_points = kwargs.pop("n_points", False)
    if n_points:
        n_samples = n_points

    if ds is not None and n_samples is not None:
        raise ValueError("ds and n_samples cannot be used together")

    if n_samples is not None:
        assert float(n_samples).is_integer(), (
            "n_samples must be a positive integer!"
        )
        assert n_samples > 1, "n_samples must be a positive integer > 1"
        # determine ds from number of desired points:
        ds = self.support.length / (n_samples - 1)

    if ds is None:
        # neither n_samples nor ds was specified, so assume defaults:
        n_samples = np.min((5000, 250 + self.n_samples // 2, self.n_samples))
        ds = self.support.length / (n_samples - 1)

    # build list of points at which to evaluate the RegularlySampledAnalogSignalArray

    # we exclude all empty intervals:
    at = []
    lengths = self.lengths
    empty_interval_ids = np.argwhere(lengths == 0).squeeze().tolist()
    first_abscissavals_per_interval_idx = np.insert(np.cumsum(lengths[:-1]), 0, 0)
    first_abscissavals_per_interval_idx[empty_interval_ids] = 0
    last_abscissavals_per_interval_idx = np.cumsum(lengths) - 1
    last_abscissavals_per_interval_idx[empty_interval_ids] = 0
    first_abscissavals_per_interval = self._abscissa_vals[
        first_abscissavals_per_interval_idx
    ]
    last_abscissavals_per_interval = self._abscissa_vals[
        last_abscissavals_per_interval_idx
    ]

    for ii, (start, stop) in enumerate(self.support.data):
        if lengths[ii] == 0:
            continue
        newxvals = utils.frange(
            first_abscissavals_per_interval[ii],
            last_abscissavals_per_interval[ii],
            step=ds,
        ).tolist()
        at.extend(newxvals)
        try:
            if newxvals[-1] < last_abscissavals_per_interval[ii]:
                at.append(last_abscissavals_per_interval[ii])
        except IndexError:
            at.append(first_abscissavals_per_interval[ii])
            at.append(last_abscissavals_per_interval[ii])

    _, yvals = self.asarray(at=at, recalculate=True, store_interp=False)
    yvals = np.array(yvals, ndmin=2)

    asa = self.copy()
    asa._abscissa_vals = np.asanyarray(at)
    asa._data = yvals
    asa._fs = 1 / ds

    return asa

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

Smooths the regularly sampled RegularlySampledAnalogSignalArray with a Gaussian kernel.

Smoothing is applied along the abscissa, and the same smoothing is applied to each signal in the RegularlySampledAnalogSignalArray, or to each unit in a BinnedSpikeTrainArray.

Smoothing is applied ACROSS intervals, but smoothing WITHIN intervals is also supported.

Parameters:

Name Type Description Default
obj RegularlySampledAnalogSignalArray or BinnedSpikeTrainArray.
required
fs float

Sampling rate (in obj.base_unit^-1) of obj. If not provided, it will be inferred.

None
sigma float

Standard deviation of Gaussian kernel, in obj.base_units. Default is 0.05 (50 ms if base_unit=seconds).

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
mode (reflect, constant, nearest, mirror, wrap)

The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to 'constant'. Default is 'reflect'.

'reflect'
cval scalar

Value to fill past edges of input if mode is 'constant'. Default is 0.0.

None
within_intervals boolean

If True, then smooth within each epoch. Otherwise smooth across epochs. Default is False. Note that when mode = 'wrap', then smoothing within epochs aren't affected by wrapping.

False

Returns:

Name Type Description
out same type as obj

An object with smoothed data is returned.

Source code in nelpy/core/_analogsignalarray.py
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
@keyword_deprecation(replace_x_with_y={"bw": "truncate"})
def smooth(
    self,
    *,
    fs=None,
    sigma=None,
    truncate=None,
    inplace=False,
    mode=None,
    cval=None,
    within_intervals=False,
):
    """Smooths the regularly sampled RegularlySampledAnalogSignalArray with a Gaussian kernel.

    Smoothing is applied along the abscissa, and the same smoothing is applied to each
    signal in the RegularlySampledAnalogSignalArray, or to each unit in a BinnedSpikeTrainArray.

    Smoothing is applied ACROSS intervals, but smoothing WITHIN intervals is also supported.

    Parameters
    ----------
    obj : RegularlySampledAnalogSignalArray or BinnedSpikeTrainArray.
    fs : float, optional
        Sampling rate (in obj.base_unit^-1) of obj. If not provided, it will
        be inferred.
    sigma : float, optional
        Standard deviation of Gaussian kernel, in obj.base_units. Default is 0.05
        (50 ms if base_unit=seconds).
    truncate : float, optional
        Bandwidth outside of which the filter value will be zero. Default is 4.0.
    inplace : bool
        If True the data will be replaced with the smoothed data.
        Default is False.
    mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
        The mode parameter determines how the array borders are handled,
        where cval is the value when mode is equal to 'constant'. Default is
        'reflect'.
    cval : scalar, optional
        Value to fill past edges of input if mode is 'constant'. Default is 0.0.
    within_intervals : boolean, optional
        If True, then smooth within each epoch. Otherwise smooth across epochs.
        Default is False.
        Note that when mode = 'wrap', then smoothing within epochs aren't affected
        by wrapping.

    Returns
    -------
    out : same type as obj
        An object with smoothed data is returned.

    """

    if sigma is None:
        sigma = 0.05
    if truncate is None:
        truncate = 4

    kwargs = {
        "inplace": inplace,
        "fs": fs,
        "sigma": sigma,
        "truncate": truncate,
        "mode": mode,
        "cval": cval,
        "within_intervals": within_intervals,
    }

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

    if self._ordinate.is_wrapping:
        ord_is_wrapped = self.is_wrapped

        if ord_is_wrapped:
            out = out.unwrap()

    # case 1: abs.wrapping=False, ord.linking=False, ord.wrapping=False
    if (
        not self._abscissa.is_wrapping
        and not self._ordinate.is_linking
        and not self._ordinate.is_wrapping
    ):
        pass

    # case 2: abs.wrapping=False, ord.linking=False, ord.wrapping=True
    elif (
        not self._abscissa.is_wrapping
        and not self._ordinate.is_linking
        and self._ordinate.is_wrapping
    ):
        pass

    # case 3: abs.wrapping=False, ord.linking=True, ord.wrapping=False
    elif (
        not self._abscissa.is_wrapping
        and self._ordinate.is_linking
        and not self._ordinate.is_wrapping
    ):
        raise NotImplementedError

    # case 4: abs.wrapping=False, ord.linking=True, ord.wrapping=True
    elif (
        not self._abscissa.is_wrapping
        and self._ordinate.is_linking
        and self._ordinate.is_wrapping
    ):
        raise NotImplementedError

    # case 5: abs.wrapping=True, ord.linking=False, ord.wrapping=False
    elif (
        self._abscissa.is_wrapping
        and not self._ordinate.is_linking
        and not self._ordinate.is_wrapping
    ):
        if mode is None:
            kwargs["mode"] = "wrap"

    # case 6: abs.wrapping=True, ord.linking=False, ord.wrapping=True
    elif (
        self._abscissa.is_wrapping
        and not self._ordinate.is_linking
        and self._ordinate.is_wrapping
    ):
        # (1) unwrap ordinate (abscissa wrap=False)
        # (2) smooth unwrapped ordinate (absissa wrap=False)
        # (3) repeat unwrapped signal based on conditions from (2):
        # if smoothed wrapped ordinate samples
        # HH ==> SSS (this must be done on a per-signal basis!!!) H = high; L = low; S = same
        # LL ==> SSS (the vertical offset must be such that neighbors have smallest displacement)
        # LH ==> LSH
        # HL ==> HSL
        # (4) smooth expanded and unwrapped ordinate (abscissa wrap=False)
        # (5) cut out orignal signal

        # (1)
        kwargs["mode"] = "reflect"
        L = out._ordinate.range.max - out._ordinate.range.min
        D = out.domain.length

        tmp = utils.gaussian_filter(out.unwrap(), **kwargs)
        # (2) (3)
        n_reps = int(np.ceil((sigma * truncate) / float(D)))

        smooth_data = []
        for ss, signal in enumerate(tmp.signals):
            # signal = signal.wrap()
            offset = (
                float((signal._data[:, -1] - signal._data[:, 0]) // (L / 2)) * L
            )
            # print(offset)
            # left_high = signal._data[:,0] >= out._ordinate.range.min + L/2
            # right_high = signal._data[:,-1] >= out._ordinate.range.min + L/2
            # signal = signal.unwrap()

            expanded = signal.copy()
            for nn in range(n_reps):
                expanded = expanded.join((signal << D * (nn + 1)) - offset).join(
                    (signal >> D * (nn + 1)) + offset
                )
                # print(expanded)
                # if left_high == right_high:
                #     print('extending flat! signal {}'.format(ss))
                #     expanded = expanded.join(signal << D*(nn+1)).join(signal >> D*(nn+1))
                # elif left_high < right_high:
                #     print('extending LSH! signal {}'.format(ss))
                #     # LSH
                #     expanded = expanded.join((signal << D*(nn+1))-L).join((signal >> D*(nn+1))+L)
                # else:
                #     # HSL
                #     print('extending HSL! signal {}'.format(ss))
                #     expanded = expanded.join((signal << D*(nn+1))+L).join((signal >> D*(nn+1))-L)
            # (4)
            smooth_signal = utils.gaussian_filter(expanded, **kwargs)
            smooth_data.append(
                smooth_signal._data[
                    :, n_reps * tmp.n_samples : (n_reps + 1) * (tmp.n_samples)
                ].squeeze()
            )
        # (5)
        out._data = np.array(smooth_data)
        out.__renew__()

        if self._ordinate.is_wrapping:
            if ord_is_wrapped:
                out = out.wrap()

        return out

    # case 7: abs.wrapping=True, ord.linking=True, ord.wrapping=False
    elif (
        self._abscissa.is_wrapping
        and self._ordinate.is_linking
        and not self._ordinate.is_wrapping
    ):
        raise NotImplementedError

    # case 8: abs.wrapping=True, ord.linking=True, ord.wrapping=True
    elif (
        self._abscissa.is_wrapping
        and self._ordinate.is_linking
        and self._ordinate.is_wrapping
    ):
        raise NotImplementedError

    out = utils.gaussian_filter(out, **kwargs)
    out.__renew__()

    if self._ordinate.is_wrapping:
        if ord_is_wrapped:
            out = out.wrap()

    return out

standardize(inplace=False)

Standardize the data to zero mean and unit standard deviation along the sample axis.

Parameters:

Name Type Description Default
inplace bool

If True, modifies the data in place. If False (default), returns a new object.

False

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

The standardized signal array.

Examples:

>>> standardized = asa.standardize()
>>> standardized.mean(), standardized.std()
(0.0, 1.0)
Source code in nelpy/core/_analogsignalarray.py
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
def standardize(self, inplace=False):
    """
    Standardize the data to zero mean and unit standard deviation along the sample axis.

    Parameters
    ----------
    inplace : bool, optional
        If True, modifies the data in place. If False (default), returns a new object.

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        The standardized signal array.

    Examples
    --------
    >>> standardized = asa.standardize()
    >>> standardized.mean(), standardized.std()
    (0.0, 1.0)
    """
    if inplace:
        out = self
    else:
        out = self.copy()
    out._data = (out._data.T - out.mean()).T
    std = np.atleast_1d(out.std())
    std[std == 0] = 1
    out._data = (out._data.T / std).T
    return out

std(*, axis=1)

Compute the standard deviation of the data along the specified axis.

Parameters:

Name Type Description Default
axis int

Axis along which to compute the standard deviation (default is 1).

1

Returns:

Name Type Description
std ndarray

Standard deviation values along the specified axis.

Source code in nelpy/core/_analogsignalarray.py
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
def std(self, *, axis=1):
    """
    Compute the standard deviation of the data along the specified axis.

    Parameters
    ----------
    axis : int, optional
        Axis along which to compute the standard deviation (default is 1).

    Returns
    -------
    std : np.ndarray
        Standard deviation values along the specified axis.
    """
    try:
        stds = np.nanstd(self.data, axis=axis).squeeze()
        if stds.size == 1:
            return stds.item()
        return stds
    except IndexError:
        raise IndexError(
            "Empty RegularlySampledAnalogSignalArray cannot calculate standard deviation"
        )

subsample(*, fs)

Subsamples a RegularlySampledAnalogSignalArray

WARNING! Aliasing can occur! It is better to use downsample when lowering the sampling rate substantially.

Parameters:

Name Type Description Default
fs float

Desired output sampling rate, in Hz

required

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

Copy of RegularlySampledAnalogSignalArray where data is only stored at the new subset of points.

Source code in nelpy/core/_analogsignalarray.py
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
def subsample(self, *, fs):
    """Subsamples a RegularlySampledAnalogSignalArray

    WARNING! Aliasing can occur! It is better to use downsample when
    lowering the sampling rate substantially.

    Parameters
    ----------
    fs : float, optional
        Desired output sampling rate, in Hz

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        Copy of RegularlySampledAnalogSignalArray where data is only stored at the
        new subset of points.
    """

    return self.simplify(ds=1 / fs)

trim(start, stop=None, *, fs=None)

Trim the signal to the specified start and stop times.

Parameters:

Name Type Description Default
start float

Start time.

required
stop float

Stop time. If None, trims to the end.

None
fs float

Sampling frequency. If None, uses self.fs.

None

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

Trimmed signal array.

Examples:

>>> trimmed = asa.trim(0, 10)
Source code in nelpy/core/_analogsignalarray.py
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
def trim(self, start, stop=None, *, fs=None):
    """
    Trim the signal to the specified start and stop times.

    Parameters
    ----------
    start : float
        Start time.
    stop : float, optional
        Stop time. If None, trims to the end.
    fs : float, optional
        Sampling frequency. If None, uses self.fs.

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        Trimmed signal array.

    Examples
    --------
    >>> trimmed = asa.trim(0, 10)
    """
    logging.warning("RegularlySampledAnalogSignalArray: Trim may not work!")
    # TODO: do comprehensive input validation
    if stop is not None:
        try:
            start = np.array(start, ndmin=1)
            if len(start) != 1:
                raise TypeError("start must be a scalar float")
        except TypeError:
            raise TypeError("start must be a scalar float")
        try:
            stop = np.array(stop, ndmin=1)
            if len(stop) != 1:
                raise TypeError("stop must be a scalar float")
        except TypeError:
            raise TypeError("stop must be a scalar float")
    else:  # start must have two elements
        try:
            if len(np.array(start, ndmin=1)) > 2:
                raise TypeError(
                    "unsupported input to RegularlySampledAnalogSignalArray.trim()"
                )
            stop = np.array(start[1], ndmin=1)
            start = np.array(start[0], ndmin=1)
            if len(start) != 1 or len(stop) != 1:
                raise TypeError("start and stop must be scalar floats")
        except TypeError:
            raise TypeError("start and stop must be scalar floats")

    logging.disable(logging.CRITICAL)
    interval = self._abscissa.support.intersect(
        type(self.support)([start, stop], fs=fs)
    )
    if not interval.isempty:
        analogsignalarray = self[interval]
    else:
        analogsignalarray = type(self)([], empty=True)
    logging.disable(0)
    analogsignalarray.__renew__()
    return analogsignalarray

unwrap(inplace=False)

Unwrap the ordinate values by minimizing total displacement, useful for phase data.

Parameters:

Name Type Description Default
inplace bool

If True, modifies the data in place. If False (default), returns a new object.

False

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

The unwrapped signal array.

Examples:

>>> unwrapped = asa.unwrap()
Source code in nelpy/core/_analogsignalarray.py
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
def unwrap(self, inplace=False):
    """
    Unwrap the ordinate values by minimizing total displacement, useful for phase data.

    Parameters
    ----------
    inplace : bool, optional
        If True, modifies the data in place. If False (default), returns a new object.

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        The unwrapped signal array.

    Examples
    --------
    >>> unwrapped = asa.unwrap()
    """
    if inplace:
        out = self
    else:
        out = self.copy()

    out.data = np.atleast_2d(
        out._unwrap(out._data, out._ordinate.range.min, out._ordinate.range.max)
    )
    # out._is_wrapped = False
    return out

wrap(inplace=False)

Wrap the ordinate values within the finite range defined by the ordinate's range.

Parameters:

Name Type Description Default
inplace bool

If True, modifies the data in place. If False (default), returns a new object.

False

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

The wrapped signal array.

Examples:

>>> wrapped = asa.wrap()
Source code in nelpy/core/_analogsignalarray.py
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
def wrap(self, inplace=False):
    """
    Wrap the ordinate values within the finite range defined by the ordinate's range.

    Parameters
    ----------
    inplace : bool, optional
        If True, modifies the data in place. If False (default), returns a new object.

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        The wrapped signal array.

    Examples
    --------
    >>> wrapped = asa.wrap()
    """
    if inplace:
        out = self
    else:
        out = self.copy()

    out.data = np.atleast_2d(
        out._wrap(out.data, out._ordinate.range.min, out._ordinate.range.max)
    )
    # out._is_wrapped = True
    return out

zscore()

Normalize each signal in the array using z-scores (zero mean, unit variance).

Returns:

Name Type Description
out RegularlySampledAnalogSignalArray

New object with z-scored data.

Examples:

>>> zscored = asa.zscore()
Source code in nelpy/core/_analogsignalarray.py
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
def zscore(self):
    """
    Normalize each signal in the array using z-scores (zero mean, unit variance).

    Returns
    -------
    out : RegularlySampledAnalogSignalArray
        New object with z-scored data.

    Examples
    --------
    >>> zscored = asa.zscore()
    """
    out = self.copy()
    out._data = zscore(out._data, axis=1)
    return out

legacyASAkwargs(**kwargs)

Provide support for legacy AnalogSignalArray kwargs.

kwarg: time <==> timestamps <==> abscissa_vals kwarg: data <==> ydata

Examples:

asa = nel.AnalogSignalArray(time=..., data=...) asa = nel.AnalogSignalArray(timestamps=..., data=...) asa = nel.AnalogSignalArray(time=..., ydata=...) asa = nel.AnalogSignalArray(ydata=...) asa = nel.AnalogSignalArray(abscissa_vals=..., data=...)

Source code in nelpy/core/_analogsignalarray.py
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
def legacyASAkwargs(**kwargs):
    """Provide support for legacy AnalogSignalArray kwargs.

    kwarg: time <==> timestamps <==> abscissa_vals
    kwarg: data <==> ydata

    Examples
    --------
    asa = nel.AnalogSignalArray(time=..., data=...)
    asa = nel.AnalogSignalArray(timestamps=..., data=...)
    asa = nel.AnalogSignalArray(time=..., ydata=...)
    asa = nel.AnalogSignalArray(ydata=...)
    asa = nel.AnalogSignalArray(abscissa_vals=..., data=...)
    """

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

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

    data = kwargs.pop("data", None)
    ydata = kwargs.pop("ydata", None)
    # only one of the above, else raise exception
    data = only_one_of(data, ydata)
    if data is not None:
        kwargs["data"] = data

    return kwargs

rsasa_init_wrapper(func)

Decorator that helps figure out abscissa_vals, fs, and sample numbers

Source code in nelpy/core/_analogsignalarray.py
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
def rsasa_init_wrapper(func):
    """Decorator that helps figure out abscissa_vals, fs, and sample numbers"""

    @wraps(func)
    def wrapper(*args, **kwargs):
        if kwargs.get("empty", False):
            func(*args, **kwargs)
            return

        if len(args) > 2:
            raise TypeError(
                "__init__() takes 1 positional arguments but {} positional arguments (and {} keyword-only arguments) were given".format(
                    len(args) - 1, len(kwargs.items())
                )
            )

        data = kwargs.get("data", [])
        if len(data) == 0:
            data = args[1]

        if len(data) == 0:
            logging.warning(
                "No ordinate data! Returning empty RegularlySampledAnalogSignalArray."
            )
            func(*args, **kwargs)
            return

        # handle casting other nelpy objects to RegularlySampledAnalogSignalArrays:
        if isinstance(data, core.BinnedEventArray):
            abscissa_vals = data.bin_centers
            kwargs["abscissa_vals"] = abscissa_vals
            # support = data.support
            # kwargs['support'] = support
            abscissa = data._abscissa
            kwargs["abscissa"] = abscissa
            fs = 1 / data.ds
            kwargs["fs"] = fs
            if list(data.series_labels):
                labels = data.series_labels
            else:
                labels = data.series_ids
            kwargs["labels"] = labels
            data = data.data.astype(float)
        # elif isinstance(data, auxiliary.PositionArray):
        elif isinstance(data, RegularlySampledAnalogSignalArray):
            kwargs["data"] = data
            func(args[0], **kwargs)
            return

        # check if single AnalogSignal or multiple AnalogSignals in array
        # and standardize data to 2D
        if not isinstance(data, np.memmap):  # memmap is a special case
            if not np.any(np.iscomplex(data)):
                data = np.squeeze(data)
        try:
            if data.shape[0] == data.size:
                data = np.expand_dims(data, axis=0)
        except ValueError:
            raise TypeError("Unsupported data type!")

        re_estimate_fs = False
        no_fs = True
        fs = kwargs.get("fs", None)
        if fs is not None:
            no_fs = False
            try:
                if fs <= 0:
                    raise ValueError("fs must be positive")
            except TypeError:
                raise TypeError("fs must be a scalar!")
        else:
            fs = 1
            re_estimate_fs = True

        tdata = kwargs.get("tdata", None)
        if tdata is not None:
            logging.warning(
                "'tdata' has been deprecated! Use 'abscissa_vals' instead. 'tdata' will be interpreted as 'abscissa_vals' in seconds."
            )
            abscissa_vals = tdata
        else:
            abscissa_vals = kwargs.get("abscissa_vals", None)
        if abscissa_vals is None:
            abscissa_vals = np.linspace(0, data.shape[1] / fs, data.shape[1] + 1)
            abscissa_vals = abscissa_vals[:-1]
        else:
            if re_estimate_fs:
                logging.warning(
                    "fs was not specified, so we try to estimate it from the data..."
                )
                fs = 1.0 / np.median(np.diff(abscissa_vals))
                logging.warning("fs was estimated to be {} Hz".format(fs))
            else:
                if no_fs:
                    logging.warning(
                        "fs was not specified, so we will assume default of 1 Hz..."
                    )
                    fs = 1

        kwargs["fs"] = fs
        kwargs["data"] = data
        kwargs["abscissa_vals"] = np.squeeze(abscissa_vals)

        func(args[0], **kwargs)
        return

    return wrapper