Skip to content

Auxiliary API Reference

nelpy auxiliary objects

nelpy is a neuroelectrophysiology object model and data analysis suite.

DirectionalTuningCurve1D

Bases: TuningCurve1D

Directional tuning curves (1-dimensional) of multiple units.

Parameters:

Name Type Description Default
bst_l2r BinnedSpikeTrainArray

Binned spike train array for left-to-right direction.

required
bst_r2l BinnedSpikeTrainArray

Binned spike train array for right-to-left direction.

required
bst_combined BinnedSpikeTrainArray

Combined binned spike train array.

required
extern array - like

External correlates (e.g., position).

required
sigma float

Standard deviation for Gaussian smoothing.

None
truncate float

Truncation parameter for smoothing.

None
n_extern int

Number of bins for external correlates.

None
transform_func callable

Function to transform external correlates.

None
minbgrate float

Minimum background firing rate.

None
extmin float

Extent of the external correlates.

0
extmax float

Extent of the external correlates.

0
extlabels list

Labels for external correlates.

None
unit_ids list

Unit IDs.

None
unit_labels list

Unit labels.

None
unit_tags list

Unit tags.

None
label str

Label for the tuning curve.

None
min_peakfiringrate float

Minimum peak firing rate.

None
max_avgfiringrate float

Maximum average firing rate.

None
unimodal bool

If True, enforce unimodality.

False
empty bool

If True, create an empty DirectionalTuningCurve1D.

False

Attributes:

Name Type Description
All attributes of TuningCurve1D, plus direction-specific attributes.
Source code in nelpy/auxiliary/_tuningcurve.py
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
class DirectionalTuningCurve1D(TuningCurve1D):
    """
    Directional tuning curves (1-dimensional) of multiple units.

    Parameters
    ----------
    bst_l2r : BinnedSpikeTrainArray
        Binned spike train array for left-to-right direction.
    bst_r2l : BinnedSpikeTrainArray
        Binned spike train array for right-to-left direction.
    bst_combined : BinnedSpikeTrainArray
        Combined binned spike train array.
    extern : array-like
        External correlates (e.g., position).
    sigma : float, optional
        Standard deviation for Gaussian smoothing.
    truncate : float, optional
        Truncation parameter for smoothing.
    n_extern : int, optional
        Number of bins for external correlates.
    transform_func : callable, optional
        Function to transform external correlates.
    minbgrate : float, optional
        Minimum background firing rate.
    extmin, extmax : float, optional
        Extent of the external correlates.
    extlabels : list, optional
        Labels for external correlates.
    unit_ids : list, optional
        Unit IDs.
    unit_labels : list, optional
        Unit labels.
    unit_tags : list, optional
        Unit tags.
    label : str, optional
        Label for the tuning curve.
    min_peakfiringrate : float, optional
        Minimum peak firing rate.
    max_avgfiringrate : float, optional
        Maximum average firing rate.
    unimodal : bool, optional
        If True, enforce unimodality.
    empty : bool, optional
        If True, create an empty DirectionalTuningCurve1D.

    Attributes
    ----------
    All attributes of TuningCurve1D, plus direction-specific attributes.
    """

    __attributes__ = ["_unit_ids_l2r", "_unit_ids_r2l"]
    __attributes__.extend(TuningCurve1D.__attributes__)

    @keyword_deprecation(replace_x_with_y={"bw": "truncate"})
    def __init__(
        self,
        *,
        bst_l2r,
        bst_r2l,
        bst_combined,
        extern,
        sigma=None,
        truncate=None,
        n_extern=None,
        transform_func=None,
        minbgrate=None,
        extmin=0,
        extmax=1,
        extlabels=None,
        unit_ids=None,
        unit_labels=None,
        unit_tags=None,
        label=None,
        empty=False,
        min_peakfiringrate=None,
        max_avgfiringrate=None,
        unimodal=False,
    ):
        """

        If sigma is nonzero, then smoothing is applied.

        We always require bst and extern, and then some combination of
            (1) bin edges, transform_func*
            (2) n_extern, transform_func*
            (3) n_extern, x_min, x_max, transform_func*

            transform_func operates on extern and returns a value that TuninCurve1D can interpret. If no transform is specified, the identity operator is assumed.
        """
        # TODO: input validation

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

        # self._bst_combined = bst_combined
        self._extern = extern

        if min_peakfiringrate is None:
            min_peakfiringrate = 1.5  # Hz minimum peak firing rate

        if max_avgfiringrate is None:
            max_avgfiringrate = 10  # Hz maximum average firing rate

        if minbgrate is None:
            minbgrate = 0.01  # Hz minimum background firing rate

        if n_extern is not None:
            if extmin is not None and extmax is not None:
                self._bins = np.linspace(extmin, extmax, n_extern + 1)
            else:
                raise NotImplementedError
        else:
            raise NotImplementedError

        self._min_peakfiringrate = min_peakfiringrate
        self._max_avgfiringrate = max_avgfiringrate
        self._unimodal = unimodal
        self._unit_ids = bst_combined.unit_ids
        self._unit_labels = bst_combined.unit_labels
        self._unit_tags = bst_combined.unit_tags  # no input validation yet
        self.label = label

        if transform_func is None:
            self.trans_func = self._trans_func

        # left to right:
        self._bst = bst_l2r
        # compute occupancy
        self._occupancy = self._compute_occupancy()
        # compute ratemap (in Hz)
        self._ratemap = self._compute_ratemap()
        # normalize firing rate by occupancy
        self._ratemap = self._normalize_firing_rate_by_occupancy()
        # enforce minimum background firing rate
        self._ratemap[self._ratemap < minbgrate] = (
            minbgrate  # background firing rate of 0.01 Hz
        )
        if sigma is not None:
            if sigma > 0:
                self.smooth(sigma=sigma, truncate=truncate, inplace=True)
        # store l2r ratemap
        ratemap_l2r = self.ratemap.copy()

        # right to left:
        self._bst = bst_r2l
        # compute occupancy
        self._occupancy = self._compute_occupancy()
        # compute ratemap (in Hz)
        self._ratemap = self._compute_ratemap()
        # normalize firing rate by occupancy
        self._ratemap = self._normalize_firing_rate_by_occupancy()
        # enforce minimum background firing rate
        self._ratemap[self._ratemap < minbgrate] = (
            minbgrate  # background firing rate of 0.01 Hz
        )
        if sigma is not None:
            if sigma > 0:
                self.smooth(sigma=sigma, truncate=truncate, inplace=True)
        # store r2l ratemap
        ratemap_r2l = self.ratemap.copy()

        # combined (non-directional):
        self._bst = bst_combined
        # compute occupancy
        self._occupancy = self._compute_occupancy()
        # compute ratemap (in Hz)
        self._ratemap = self._compute_ratemap()
        # normalize firing rate by occupancy
        self._ratemap = self._normalize_firing_rate_by_occupancy()
        # enforce minimum background firing rate
        self._ratemap[self._ratemap < minbgrate] = (
            minbgrate  # background firing rate of 0.01 Hz
        )
        if sigma is not None:
            if sigma > 0:
                self.smooth(sigma=sigma, truncate=truncate, inplace=True)
        # store combined ratemap
        # ratemap = self.ratemap

        # determine unit membership:
        l2r_unit_ids = self.restrict_units(ratemap_l2r)
        r2l_unit_ids = self.restrict_units(ratemap_r2l)

        common_unit_ids = list(r2l_unit_ids.intersection(l2r_unit_ids))
        l2r_only_unit_ids = list(l2r_unit_ids.difference(common_unit_ids))
        r2l_only_unit_ids = list(r2l_unit_ids.difference(common_unit_ids))

        # update ratemap with directional tuning curves
        for unit_id in l2r_only_unit_ids:
            unit_idx = self.unit_ids.index(unit_id)
            # print('replacing', self._ratemap[unit_idx, :])
            # print('with', ratemap_l2r[unit_idx, :])
            self._ratemap[unit_idx, :] = ratemap_l2r[unit_idx, :]
        for unit_id in r2l_only_unit_ids:
            unit_idx = self.unit_ids.index(unit_id)
            self._ratemap[unit_idx, :] = ratemap_r2l[unit_idx, :]

        self._unit_ids_l2r = l2r_only_unit_ids
        self._unit_ids_r2l = r2l_only_unit_ids

        # optionally detach _bst and _extern to save space when pickling, for example
        self._detach()

    def restrict_units(self, ratemap=None):
        if ratemap is None:
            ratemap = self.ratemap

        # enforce minimum peak firing rate
        unit_ids_to_keep = set(
            np.asanyarray(self.unit_ids)[
                np.argwhere(ratemap.max(axis=1) > self._min_peakfiringrate)
                .squeeze()
                .tolist()
            ]
        )
        # enforce maximum average firing rate
        unit_ids_to_keep = unit_ids_to_keep.intersection(
            set(
                np.asanyarray(self.unit_ids)[
                    np.argwhere(ratemap.mean(axis=1) < self._max_avgfiringrate)
                    .squeeze()
                    .tolist()
                ]
            )
        )
        # remove multimodal units
        if self._unimodal:
            raise NotImplementedError(
                "restriction to unimodal cells not yet implemented!"
            )
            # placecellidx = placecellidx.intersection(set(unimodal_cells))

        return unit_ids_to_keep

    @property
    def unit_ids_l2r(self):
        return self._unit_ids_l2r

    @property
    def unit_ids_r2l(self):
        return self._unit_ids_r2l

ResultsContainer

Bases: object

Extremely simple namespace for passing around and pickling data.

This container is used to group, store, and load results from analyses or experiments.

Parameters:

Name Type Description Default
description str

Description of the results container.

None
**kwargs

Additional attributes to store in the container.

{}

Attributes:

Name Type Description
description str

Description of the results container.

_index int

Internal index for iteration.

Source code in nelpy/auxiliary/_results.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 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
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
class ResultsContainer(object):
    """
    Extremely simple namespace for passing around and pickling data.

    This container is used to group, store, and load results from analyses or experiments.

    Parameters
    ----------
    description : str, optional
        Description of the results container.
    **kwargs :
        Additional attributes to store in the container.

    Attributes
    ----------
    description : str
        Description of the results container.
    _index : int
        Internal index for iteration.
    """

    def __init__(self, *args, description=None, **kwargs):
        """
        Initialize a ResultsContainer.

        Parameters
        ----------
        description : str, optional
            Description of the results container.
        **kwargs :
            Additional attributes to store in the container.
        """
        kwargs["description"] = description

        if len(args) > 0:
            raise NotImplementedError("only keyword arguments accepted!")

        for key, val in kwargs.items():
            setattr(self, key, val)

        self._index = 0

    # def __init__(self, *args, description=None, **kwargs):
    #     kwargs['description'] = description

    #     # BEGIN very hacky code to get *args names; might break!
    #     # see http://stackoverflow.com/questions/2749796/how-to-get-the-original-variable-name-of-variable-passed-to-a-function
    #     frame = inspect.currentframe()
    #     frame = inspect.getouterframes(frame)[1]
    #     string = inspect.getframeinfo(frame[0]).code_context[0].strip()
    #     _args = string[string.find('(') + 1:-1].split(',')

    #     names = []
    #     for i in _args:
    #         if i.find('=') != -1:
    #             pass
    #             # names.append(i.split('=')[1].strip())
    #         else:
    #             names.append(i)

    #     for ii, arg in enumerate(args):
    #         setattr(self, names[ii], arg)
    #     # END very hacky code to get *args names; might break!

    #     for key, val in kwargs.items():
    #         setattr(self, key, val)

    #     self.description = None

    def __repr__(self):
        """
        Return a string representation of the ResultsContainer.

        Returns
        -------
        repr_str : str
            String representation of the ResultsContainer, including address, number of objects, and description.
        """
        if self.isempty:
            return "<Empty ResultsContainer>"
        if self.n_objects == 1:
            n_str = " (" + str(self.n_objects) + " object)"
        else:
            n_str = " (" + str(self.n_objects) + " objects)"
        address_str = " at " + str(hex(id(self)))
        descr_str = ""
        if self.description is not None:
            descr_str = "\n**Description:** " + str(self.description)
        return "<ResultsContainer" + address_str + n_str + ">" + descr_str

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

    # def __next__(self):
    #     index = self._index

    #     if index > self.n_objects - 1:
    #         raise StopIteration
    #     self._index += 1
    #     return self[index]

    # def __getitem__(self, idx):
    #     keys = [key for key in self.__dict__ if key not in ['description', '_index']]
    #     keys.sort()
    #     return keys[idx]

    @property
    def isempty(self):
        """Empty ResultsContainer."""
        return self.n_objects == 0

    @property
    def n_objects(self):
        """(int) Number of objects in ResultsContainer."""
        return len(list(self.__dict__.values())) - 2

    @property
    def keys(self):
        """(list) Key names in ResultsContainer."""
        keys = [key for key in self.__dict__ if key not in ["description", "_index"]]
        keys.sort()
        return keys

    def save_pkl(self, fname, zip=True, overwrite=False):
        """Write pickled data to disk, possible compressing."""
        if os.path.isfile(fname):
            # file exists
            if overwrite:
                pass
            else:
                print('File "{}" already exists! Aborting...'.format(fname))
                return
        if zip:
            save_large_file_without_zip = False
            with gzip.open(fname, "wb") as fid:
                try:
                    pickle.dump(self, fid)
                except OverflowError:
                    print(
                        "writing to disk using protocol=4, which supports file sizes > 4 GiB, and ignoring zip=True (zip is not supported for large files yet)"
                    )
                    save_large_file_without_zip = True

            if save_large_file_without_zip:
                with open(fname, "wb") as fid:
                    pickle.dump(self, fid, protocol=4)
        else:
            with open(fname, "wb") as fid:
                try:
                    pickle.dump(self, fid)
                except OverflowError:
                    print(
                        "writing to disk using protocol=4, which supports file sizes > 4 GiB"
                    )
                    pickle.dump(self, fid, protocol=4)

isempty property

Empty ResultsContainer.

keys property

(list) Key names in ResultsContainer.

n_objects property

(int) Number of objects in ResultsContainer.

save_pkl(fname, zip=True, overwrite=False)

Write pickled data to disk, possible compressing.

Source code in nelpy/auxiliary/_results.py
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
def save_pkl(self, fname, zip=True, overwrite=False):
    """Write pickled data to disk, possible compressing."""
    if os.path.isfile(fname):
        # file exists
        if overwrite:
            pass
        else:
            print('File "{}" already exists! Aborting...'.format(fname))
            return
    if zip:
        save_large_file_without_zip = False
        with gzip.open(fname, "wb") as fid:
            try:
                pickle.dump(self, fid)
            except OverflowError:
                print(
                    "writing to disk using protocol=4, which supports file sizes > 4 GiB, and ignoring zip=True (zip is not supported for large files yet)"
                )
                save_large_file_without_zip = True

        if save_large_file_without_zip:
            with open(fname, "wb") as fid:
                pickle.dump(self, fid, protocol=4)
    else:
        with open(fname, "wb") as fid:
            try:
                pickle.dump(self, fid)
            except OverflowError:
                print(
                    "writing to disk using protocol=4, which supports file sizes > 4 GiB"
                )
                pickle.dump(self, fid, protocol=4)

Session

Nelpy session with common clock.

Source code in nelpy/auxiliary/_session.py
22
23
24
25
26
27
28
29
30
31
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
class Session:
    """Nelpy session with common clock."""

    __attributes__ = ["_animal", "_label", "_st", "_extern", "_mua"]

    def __init__(
        self, animal=None, st=None, extern=None, mua=None, label=None, empty=False
    ):
        # if an empty object is requested, return it:
        if empty:
            for attr in self.__attributes__:
                exec("self." + attr + " = None")
            return

        self._animal = animal
        self._extern = extern
        self._st = st
        self._mua = mua
        self.label = label

    @property
    def animal(self):
        return self._animal

    @property
    def extern(self):
        return self._extern

    @property
    def st(self):
        return self._st

    @property
    def mua(self):
        return self._mua

    @property
    def label(self):
        """Label pertaining to the source of the spike train."""
        if self._label is None:
            warnings.warn("label has not yet been specified")
        return self._label

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

label property writable

Label pertaining to the source of the spike train.

TuningCurve1D

Tuning curves (1-dimensional) of multiple units.

Parameters:

Name Type Description Default
bst BinnedSpikeTrainArray

Binned spike train array for tuning curve estimation.

None
extern array - like

External correlates (e.g., position).

None
ratemap ndarray

Precomputed rate map.

None
sigma float

Standard deviation for Gaussian smoothing.

None
truncate float

Truncation parameter for smoothing.

None
n_extern int

Number of bins for external correlates.

None
transform_func callable

Function to transform external correlates.

None
minbgrate float

Minimum background firing rate.

None
extmin float

Extent of the external correlates.

0
extmax float

Extent of the external correlates.

0
extlabels list

Labels for external correlates.

None
unit_ids list

Unit IDs.

None
unit_labels list

Unit labels.

None
unit_tags list

Unit tags.

None
label str

Label for the tuning curve.

None
min_duration float

Minimum duration for occupancy.

None
empty bool

If True, create an empty TuningCurve1D.

False

Attributes:

Name Type Description
ratemap ndarray

The 1D rate map.

occupancy ndarray

Occupancy map.

unit_ids list

Unit IDs.

unit_labels list

Unit labels.

unit_tags list

Unit tags.

label str

Label for the tuning curve.

Source code in nelpy/auxiliary/_tuningcurve.py
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
class TuningCurve1D:
    """
    Tuning curves (1-dimensional) of multiple units.

    Parameters
    ----------
    bst : BinnedSpikeTrainArray, optional
        Binned spike train array for tuning curve estimation.
    extern : array-like, optional
        External correlates (e.g., position).
    ratemap : np.ndarray, optional
        Precomputed rate map.
    sigma : float, optional
        Standard deviation for Gaussian smoothing.
    truncate : float, optional
        Truncation parameter for smoothing.
    n_extern : int, optional
        Number of bins for external correlates.
    transform_func : callable, optional
        Function to transform external correlates.
    minbgrate : float, optional
        Minimum background firing rate.
    extmin, extmax : float, optional
        Extent of the external correlates.
    extlabels : list, optional
        Labels for external correlates.
    unit_ids : list, optional
        Unit IDs.
    unit_labels : list, optional
        Unit labels.
    unit_tags : list, optional
        Unit tags.
    label : str, optional
        Label for the tuning curve.
    min_duration : float, optional
        Minimum duration for occupancy.
    empty : bool, optional
        If True, create an empty TuningCurve1D.

    Attributes
    ----------
    ratemap : np.ndarray
        The 1D rate map.
    occupancy : np.ndarray
        Occupancy map.
    unit_ids : list
        Unit IDs.
    unit_labels : list
        Unit labels.
    unit_tags : list
        Unit tags.
    label : str
        Label for the tuning curve.
    """

    __attributes__ = [
        "_ratemap",
        "_occupancy",
        "_unit_ids",
        "_unit_labels",
        "_unit_tags",
        "_label",
    ]

    @keyword_deprecation(replace_x_with_y={"bw": "truncate"})
    def __init__(
        self,
        *,
        bst=None,
        extern=None,
        ratemap=None,
        sigma=None,
        truncate=None,
        n_extern=None,
        transform_func=None,
        minbgrate=None,
        extmin=0,
        extmax=1,
        extlabels=None,
        unit_ids=None,
        unit_labels=None,
        unit_tags=None,
        label=None,
        min_duration=None,
        empty=False,
    ):
        """

        If sigma is nonzero, then smoothing is applied.

        We always require bst and extern, and then some combination of
            (1) bin edges, transform_func*
            (2) n_extern, transform_func*
            (3) n_extern, x_min, x_max, transform_func*

            transform_func operates on extern and returns a value that TuninCurve1D can interpret. If no transform is specified, the identity operator is assumed.
        """
        # TODO: input validation
        if not empty:
            if ratemap is None:
                assert bst is not None, (
                    "bst must be specified or ratemap must be specified!"
                )
                assert extern is not None, (
                    "extern must be specified or ratemap must be specified!"
                )
            else:
                assert bst is None, "ratemap and bst cannot both be specified!"
                assert extern is None, "ratemap and extern cannot both be specified!"

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

        if ratemap is not None:
            for attr in self.__attributes__:
                exec("self." + attr + " = None")
            self._init_from_ratemap(
                ratemap=ratemap,
                extmin=extmin,
                extmax=extmax,
                extlabels=extlabels,
                unit_ids=unit_ids,
                unit_labels=unit_labels,
                unit_tags=unit_tags,
                label=label,
            )
            return

        self._bst = bst
        self._extern = extern

        if minbgrate is None:
            minbgrate = 0.01  # Hz minimum background firing rate

        if n_extern is not None:
            if extmin is not None and extmax is not None:
                self._bins = np.linspace(extmin, extmax, n_extern + 1)
            else:
                raise NotImplementedError
        else:
            raise NotImplementedError

        if min_duration is None:
            min_duration = 0

        self._min_duration = min_duration

        self._unit_ids = bst.unit_ids
        self._unit_labels = bst.unit_labels
        self._unit_tags = bst.unit_tags  # no input validation yet
        self.label = label

        if transform_func is None:
            self.trans_func = self._trans_func

        # compute occupancy
        self._occupancy = self._compute_occupancy()
        # compute ratemap (in Hz)
        self._ratemap = self._compute_ratemap()
        # normalize firing rate by occupancy
        self._ratemap = self._normalize_firing_rate_by_occupancy()
        # enforce minimum background firing rate
        self._ratemap[self._ratemap < minbgrate] = (
            minbgrate  # background firing rate of 0.01 Hz
        )

        if sigma is not None:
            if sigma > 0:
                self.smooth(sigma=sigma, truncate=truncate, inplace=True)

        # optionally detach _bst and _extern to save space when pickling, for example
        self._detach()

    @property
    def is2d(self):
        return False

    def spatial_information(self):
        """Compute the spatial information...

        The specificity index examines the amount of information
        (in bits) that a single spike conveys about the animal's
        location (i.e., how well cell firing predicts the animal's
        location).The spatial information content of cell discharge was
        calculated using the formula:
            information content = \Sum P_i(R_i/R)log_2(R_i/R)
        where i is the bin number, P_i, is the probability for occupancy
        of bin i, R_i, is the mean firing rate for bin i, and R is the
        overall mean firing rate.

        In order to account for the effects of low firing rates (with
        fewer spikes there is a tendency toward higher information
        content) or random bursts of firing, the spike firing
        time-series was randomly offset in time from the rat location
        time-series, and the information content was calculated. A
        distribution of the information content based on 100 such random
        shifts was obtained and was used to compute a standardized score
        (Zscore) of information content for that cell. While the
        distribution is not composed of independent samples, it was
        nominally normally distributed, and a Z value of 2.29 was chosen
        as a cut-off for significance (the equivalent of a one-tailed
        t-test with P = 0.01 under a normal distribution).

        Reference(s)
        ------------
        Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L.,
            and Skaggs, W. E. (1994). "Spatial information content and
            reliability of hippocampal CA1 neurons: effects of visual
            input", Hippocampus, 4(4), 410-421.

        Parameters
        ----------

        Returns
        -------
        si : array of shape (n_units,)
            spatial information (in bits) per unit
        sparsity: array of shape (n_units,)
            sparsity (in percent) for each unit
        """

        return utils.spatial_information(ratemap=self.ratemap, Pi=self.occupancy)

    def information_rate(self):
        """Compute the information rate..."""
        return utils.information_rate(ratemap=self.ratemap, Pi=self.occupancy)

    def spatial_selectivity(self):
        """Compute the spatial selectivity..."""
        return utils.spatial_selectivity(ratemap=self.ratemap, Pi=self.occupancy)

    def spatial_sparsity(self):
        """Compute the firing sparsity...

        Parameters
        ----------

        Returns
        -------
        si : array of shape (n_units,)
            spatial information (in bits) per unit
        sparsity: array of shape (n_units,)
            sparsity (in percent) for each unit
        """
        return utils.spatial_sparsity(ratemap=self.ratemap, Pi=self.occupancy)

    def _init_from_ratemap(
        self,
        ratemap,
        occupancy=None,
        extmin=0,
        extmax=1,
        extlabels=None,
        unit_ids=None,
        unit_labels=None,
        unit_tags=None,
        label=None,
    ):
        """Initialize a TuningCurve1D object from a ratemap.

        Parameters
        ----------
        ratemap : array
            Array of shape (n_units, n_extern)

        Returns
        -------

        """
        n_units, n_extern = ratemap.shape

        if occupancy is None:
            # assume uniform occupancy
            self._occupancy = np.ones(n_extern)

        if extmin is None:
            extmin = 0
        if extmax is None:
            extmax = extmin + 1

        self._bins = np.linspace(extmin, extmax, n_extern + 1)
        self._ratemap = ratemap

        # inherit unit IDs if available, otherwise initialize to default
        if unit_ids is None:
            unit_ids = list(range(1, n_units + 1))

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

        # if unit_labels is empty, default to unit_ids
        if unit_labels is None:
            unit_labels = unit_ids

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

        self._unit_ids = unit_ids
        self._unit_labels = unit_labels
        self._unit_tags = unit_tags  # no input validation yet
        if label is not None:
            self.label = label

        return self

    def mean(self, *, axis=None):
        """Returns the mean of firing rate (in Hz).
        Parameters
        ----------
        axis : int, optional
            When axis is None, the global mean firing rate is returned.
            When axis is 0, the mean firing rates across units, as a
            function of the external correlate (e.g. position) are
            returned.
            When axis is 1, the mean firing rate for each unit is
            returned.
        Returns
        -------
        mean :
        """
        means = np.mean(self.ratemap, axis=axis).squeeze()
        if means.size == 1:
            return np.asarray(means).item()
        return means

    def max(self, *, axis=None):
        """Returns the mean of firing rate (in Hz).
        Parameters
        ----------
        axis : int, optional
            When axis is None, the global mean firing rate is returned.
            When axis is 0, the mean firing rates across units, as a
            function of the external correlate (e.g. position) are
            returned.
            When axis is 1, the mean firing rate for each unit is
            returned.
        Returns
        -------
        mean :
        """
        maxes = np.max(self.ratemap, axis=axis).squeeze()
        if maxes.size == 1:
            return np.asarray(maxes).item()
        return maxes

    def min(self, *, axis=None):
        """Returns the mean of firing rate (in Hz).
        Parameters
        ----------
        axis : int, optional
            When axis is None, the global mean firing rate is returned.
            When axis is 0, the mean firing rates across units, as a
            function of the external correlate (e.g. position) are
            returned.
            When axis is 1, the mean firing rate for each unit is
            returned.
        Returns
        -------
        mean :
        """
        mins = np.min(self.ratemap, axis=axis).squeeze()
        if mins.size == 1:
            return np.asarray(mins).item()
        return mins

    @property
    def ratemap(self):
        return self._ratemap

    @property
    def n_bins(self):
        """(int) Number of external correlates (bins)."""
        return len(self.bins) - 1

    @property
    def occupancy(self):
        return self._occupancy

    @property
    def bins(self):
        """External correlate bins."""
        return self._bins

    @property
    def bin_centers(self):
        """External correlate bin centers."""
        return (self.bins + (self.bins[1] - self.bins[0]) / 2)[:-1]

    def _trans_func(self, extern, at):
        """Default transform function to map extern into numerical bins"""

        _, ext = extern.asarray(at=at)

        return np.atleast_1d(ext)

    def _compute_occupancy(self):
        # Make sure that self._bst_centers fall within not only the support
        # of extern, but also within the extreme sample times; otherwise,
        # interpolation will yield NaNs at the extremes. Indeed, when we have
        # sample times within a support epoch, we can assume that the signal
        # stayed roughly constant for that one sample duration.

        if self._bst._bin_centers[0] < self._extern.time[0]:
            self._extern = copy.copy(self._extern)
            self._extern.time[0] = self._bst._bin_centers[0]
            self._extern._interp = None
            # raise ValueError('interpolated sample requested before first sample of extern!')
        if self._bst._bin_centers[-1] > self._extern.time[-1]:
            self._extern = copy.copy(self._extern)
            self._extern.time[-1] = self._bst._bin_centers[-1]
            self._extern._interp = None
            # raise ValueError('interpolated sample requested after last sample of extern!')

        ext = self.trans_func(self._extern, at=self._bst.bin_centers)

        xmin = self.bins[0]
        xmax = self.bins[-1]
        occupancy, _ = np.histogram(ext, bins=self.bins, range=(xmin, xmax))
        # xbins = (bins + xmax/n_xbins)[:-1] # for plotting
        return occupancy

    def _compute_ratemap(self, min_duration=None):
        if min_duration is None:
            min_duration = self._min_duration

        ext = self.trans_func(self._extern, at=self._bst.bin_centers)

        ext_bin_idx = np.squeeze(np.digitize(ext, self.bins, right=True))
        # make sure that all the events fit between extmin and extmax:
        # TODO: this might rather be a warning, but it's a pretty serious warning...
        if ext_bin_idx.max() > self.n_bins:
            raise ValueError("ext values greater than 'ext_max'")
        if ext_bin_idx.min() == 0:
            raise ValueError("ext values less than 'ext_min'")

        ratemap = np.zeros((self.n_units, self.n_bins))

        for tt, bidx in enumerate(ext_bin_idx):
            ratemap[:, bidx - 1] += self._bst.data[:, tt]

        # apply minimum observation duration
        for uu in range(self.n_units):
            ratemap[uu][self.occupancy * self._bst.ds < min_duration] = 0

        return ratemap / self._bst.ds

    def normalize(self, inplace=False):
        if not inplace:
            out = copy.deepcopy(self)
        else:
            out = self
        if self.n_units > 1:
            per_unit_max = np.max(out.ratemap, axis=1)[..., np.newaxis]
            out._ratemap = self.ratemap / np.tile(per_unit_max, (1, out.n_bins))
        else:
            per_unit_max = np.max(out.ratemap)
            out._ratemap = self.ratemap / np.tile(per_unit_max, out.n_bins)
        return out

    def _normalize_firing_rate_by_occupancy(self):
        # normalize spike counts by occupancy:
        denom = np.tile(self.occupancy, (self.n_units, 1))
        denom[denom == 0] = 1
        ratemap = self.ratemap / denom
        return ratemap

    @property
    def unit_ids(self):
        """Unit IDs contained in the SpikeTrain."""
        return list(self._unit_ids)

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

    @property
    def unit_labels(self):
        """Labels corresponding to units contained in the SpikeTrain."""
        if self._unit_labels is None:
            warnings.warn("unit labels have not yet been specified")
        return self._unit_labels

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

    @property
    def unit_tags(self):
        """Tags corresponding to units contained in the SpikeTrain"""
        if self._unit_tags is None:
            warnings.warn("unit tags have not yet been specified")
        return self._unit_tags

    @property
    def label(self):
        """Label pertaining to the source of the spike train."""
        if self._label is None:
            warnings.warn("label has not yet been specified")
        return self._label

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

    def __add__(self, other):
        out = copy.copy(self)

        if isinstance(other, numbers.Number):
            out._ratemap = out.ratemap + other
        elif isinstance(other, TuningCurve1D):
            # TODO: this should merge two TuningCurve1D objects
            raise NotImplementedError
        else:
            raise TypeError(
                "unsupported operand type(s) for +: 'TuningCurve1D' and '{}'".format(
                    str(type(other))
                )
            )
        return out

    def __sub__(self, other):
        out = copy.copy(self)
        out._ratemap = out.ratemap - other
        return out

    def __mul__(self, other):
        """overloaded * operator."""
        out = copy.copy(self)
        out._ratemap = out.ratemap * other
        return out

    def __rmul__(self, other):
        return self * other

    def __truediv__(self, other):
        """overloaded / operator."""
        out = copy.copy(self)
        out._ratemap = out.ratemap / other
        return out

    def __len__(self):
        return self.n_units

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

        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
        """
        if sigma is None:
            sigma = 0.1  # in units of extern
        if truncate is None:
            truncate = 4
        if mode is None:
            mode = "reflect"
        if cval is None:
            cval = 0.0

        ds = (self.bins[-1] - self.bins[0]) / self.n_bins
        sigma = sigma / ds

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

        if self.n_units > 1:
            out._ratemap = scipy.ndimage.filters.gaussian_filter(
                self.ratemap, sigma=(0, sigma), truncate=truncate, mode=mode, cval=cval
            )
        else:
            out._ratemap = scipy.ndimage.filters.gaussian_filter(
                self.ratemap, sigma=sigma, truncate=truncate, mode=mode, cval=cval
            )

        return out

    @property
    def n_units(self):
        """(int) The number of units."""
        try:
            return len(self._unit_ids)
        except TypeError:  # when unit_ids is an integer
            return 1
        except AttributeError:
            return 0

    @property
    def shape(self):
        """(tuple) The shape of the TuningCurve1D ratemap."""
        if self.isempty:
            return (self.n_units, 0)
        if len(self.ratemap.shape) == 1:
            return (1, self.ratemap.shape[0])
        return self.ratemap.shape

    def __repr__(self):
        address_str = " at " + str(hex(id(self)))
        if self.isempty:
            return "<empty TuningCurve1D" + address_str + ">"
        shapestr = " with shape (%s, %s)" % (self.shape[0], self.shape[1])
        return "<TuningCurve1D%s>%s" % (address_str, shapestr)

    @property
    def isempty(self):
        """(bool) True if TuningCurve1D is empty"""
        try:
            return len(self.ratemap) == 0
        except TypeError:  # TypeError should happen if ratemap = []
            return True

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

    def __next__(self):
        """TuningCurve1D iterator advancer."""
        index = self._index
        if index > self.n_units - 1:
            raise StopIteration
        out = copy.copy(self)
        out._ratemap = self.ratemap[index, :]
        out._unit_ids = self.unit_ids[index]
        out._unit_labels = self.unit_labels[index]
        self._index += 1
        return out

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

        Accepts integers, slices, and lists"""

        idx = [ii for ii in idx]
        if len(idx) == 1 and not isinstance(idx[0], int):
            idx = idx[0]
        if isinstance(idx, tuple):
            idx = [ii for ii in idx]

        if self.isempty:
            return self
        try:
            out = copy.copy(self)
            out._ratemap = self.ratemap[idx, :]
            out._unit_ids = (np.asanyarray(out._unit_ids)[idx]).tolist()
            out._unit_labels = (np.asanyarray(out._unit_labels)[idx]).tolist()
            return out
        except Exception:
            raise TypeError("unsupported subsctipting type {}".format(type(idx)))

    def _unit_subset(self, unit_list):
        """Return a TuningCurve1D restricted to a subset of units.

        Parameters
        ----------
        unit_list : array-like
            Array or list of unit_ids.
        """
        unit_subset_ids = []
        for unit in unit_list:
            try:
                id = self.unit_ids.index(unit)
            except ValueError:
                warnings.warn(
                    "unit_id " + str(unit) + " not found in TuningCurve1D; ignoring"
                )
                pass
            else:
                unit_subset_ids.append(id)

        new_unit_ids = (np.asarray(self.unit_ids)[unit_subset_ids]).tolist()
        new_unit_labels = (np.asarray(self.unit_labels)[unit_subset_ids]).tolist()

        if len(unit_subset_ids) == 0:
            warnings.warn("no units remaining in requested unit subset")
            return TuningCurve1D(empty=True)

        newtuningcurve = copy.copy(self)
        newtuningcurve._unit_ids = new_unit_ids
        newtuningcurve._unit_labels = new_unit_labels
        # TODO: implement tags
        # newtuningcurve._unit_tags =
        newtuningcurve._ratemap = self.ratemap[unit_subset_ids, :]
        # TODO: shall we restrict _bst as well? This will require a copy to be made...
        # newtuningcurve._bst =

        return newtuningcurve

    def _get_peak_firing_order_idx(self):
        """Docstring goes here

        ratemap has shape (n_units, n_ext)
        """
        peakorder = np.argmax(self.ratemap, axis=1).argsort()

        return peakorder.tolist()

    def get_peak_firing_order_ids(self):
        """Docstring goes here

        ratemap has shape (n_units, n_ext)
        """
        peakorder = np.argmax(self.ratemap, axis=1).argsort()

        return (np.asanyarray(self.unit_ids)[peakorder]).tolist()

    def _reorder_units_by_idx(self, neworder=None, *, inplace=False):
        """Reorder units according to a specified order.

        neworder must be list-like, of size (n_units,) and in 0,..n_units
        and not in terms of unit_ids

        Return
        ------
        out : reordered TuningCurve1D
        """
        if neworder is None:
            neworder = self._get_peak_firing_order_idx()
        if inplace:
            out = self
        else:
            out = copy.deepcopy(self)

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

        return out

    def reorder_units_by_ids(self, neworder=None, *, inplace=False):
        """Reorder units according to a specified order.

        neworder must be list-like, of size (n_units,) and in terms of
        unit_ids

        Return
        ------
        out : reordered TuningCurve1D
        """
        if neworder is None:
            neworder = self.get_peak_firing_order_ids()
        if inplace:
            out = self
        else:
            out = copy.deepcopy(self)

        # unit_ids = list(unit_ids)
        neworder = [self.unit_ids.index(x) for x in neworder]

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

        return out

    def reorder_units(self, inplace=False):
        """Convenience function to reorder units by peak firing location."""
        return self.reorder_units_by_ids(inplace=inplace)

    def _detach(self):
        """Detach bst and extern from tuning curve."""
        self._bst = None
        self._extern = None

bin_centers property

External correlate bin centers.

bins property

External correlate bins.

isempty property

(bool) True if TuningCurve1D is empty

label property writable

Label pertaining to the source of the spike train.

n_bins property

(int) Number of external correlates (bins).

n_units property

(int) The number of units.

shape property

(tuple) The shape of the TuningCurve1D ratemap.

unit_ids property writable

Unit IDs contained in the SpikeTrain.

unit_labels property writable

Labels corresponding to units contained in the SpikeTrain.

unit_tags property

Tags corresponding to units contained in the SpikeTrain

get_peak_firing_order_ids()

Docstring goes here

ratemap has shape (n_units, n_ext)

Source code in nelpy/auxiliary/_tuningcurve.py
1756
1757
1758
1759
1760
1761
1762
1763
def get_peak_firing_order_ids(self):
    """Docstring goes here

    ratemap has shape (n_units, n_ext)
    """
    peakorder = np.argmax(self.ratemap, axis=1).argsort()

    return (np.asanyarray(self.unit_ids)[peakorder]).tolist()

information_rate()

Compute the information rate...

Source code in nelpy/auxiliary/_tuningcurve.py
1251
1252
1253
def information_rate(self):
    """Compute the information rate..."""
    return utils.information_rate(ratemap=self.ratemap, Pi=self.occupancy)

max(*, axis=None)

Returns the mean of firing rate (in Hz).

Parameters:

Name Type Description Default
axis int

When axis is None, the global mean firing rate is returned. When axis is 0, the mean firing rates across units, as a function of the external correlate (e.g. position) are returned. When axis is 1, the mean firing rate for each unit is returned.

None

Returns:

Name Type Description
mean
Source code in nelpy/auxiliary/_tuningcurve.py
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
def max(self, *, axis=None):
    """Returns the mean of firing rate (in Hz).
    Parameters
    ----------
    axis : int, optional
        When axis is None, the global mean firing rate is returned.
        When axis is 0, the mean firing rates across units, as a
        function of the external correlate (e.g. position) are
        returned.
        When axis is 1, the mean firing rate for each unit is
        returned.
    Returns
    -------
    mean :
    """
    maxes = np.max(self.ratemap, axis=axis).squeeze()
    if maxes.size == 1:
        return np.asarray(maxes).item()
    return maxes

mean(*, axis=None)

Returns the mean of firing rate (in Hz).

Parameters:

Name Type Description Default
axis int

When axis is None, the global mean firing rate is returned. When axis is 0, the mean firing rates across units, as a function of the external correlate (e.g. position) are returned. When axis is 1, the mean firing rate for each unit is returned.

None

Returns:

Name Type Description
mean
Source code in nelpy/auxiliary/_tuningcurve.py
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
def mean(self, *, axis=None):
    """Returns the mean of firing rate (in Hz).
    Parameters
    ----------
    axis : int, optional
        When axis is None, the global mean firing rate is returned.
        When axis is 0, the mean firing rates across units, as a
        function of the external correlate (e.g. position) are
        returned.
        When axis is 1, the mean firing rate for each unit is
        returned.
    Returns
    -------
    mean :
    """
    means = np.mean(self.ratemap, axis=axis).squeeze()
    if means.size == 1:
        return np.asarray(means).item()
    return means

min(*, axis=None)

Returns the mean of firing rate (in Hz).

Parameters:

Name Type Description Default
axis int

When axis is None, the global mean firing rate is returned. When axis is 0, the mean firing rates across units, as a function of the external correlate (e.g. position) are returned. When axis is 1, the mean firing rate for each unit is returned.

None

Returns:

Name Type Description
mean
Source code in nelpy/auxiliary/_tuningcurve.py
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
def min(self, *, axis=None):
    """Returns the mean of firing rate (in Hz).
    Parameters
    ----------
    axis : int, optional
        When axis is None, the global mean firing rate is returned.
        When axis is 0, the mean firing rates across units, as a
        function of the external correlate (e.g. position) are
        returned.
        When axis is 1, the mean firing rate for each unit is
        returned.
    Returns
    -------
    mean :
    """
    mins = np.min(self.ratemap, axis=axis).squeeze()
    if mins.size == 1:
        return np.asarray(mins).item()
    return mins

reorder_units(inplace=False)

Convenience function to reorder units by peak firing location.

Source code in nelpy/auxiliary/_tuningcurve.py
1838
1839
1840
def reorder_units(self, inplace=False):
    """Convenience function to reorder units by peak firing location."""
    return self.reorder_units_by_ids(inplace=inplace)

reorder_units_by_ids(neworder=None, *, inplace=False)

Reorder units according to a specified order.

neworder must be list-like, of size (n_units,) and in terms of unit_ids

Return

out : reordered TuningCurve1D

Source code in nelpy/auxiliary/_tuningcurve.py
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
def reorder_units_by_ids(self, neworder=None, *, inplace=False):
    """Reorder units according to a specified order.

    neworder must be list-like, of size (n_units,) and in terms of
    unit_ids

    Return
    ------
    out : reordered TuningCurve1D
    """
    if neworder is None:
        neworder = self.get_peak_firing_order_ids()
    if inplace:
        out = self
    else:
        out = copy.deepcopy(self)

    # unit_ids = list(unit_ids)
    neworder = [self.unit_ids.index(x) for x in neworder]

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

    return out

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

Smooths the tuning curve with a Gaussian kernel.

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

Source code in nelpy/auxiliary/_tuningcurve.py
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
@keyword_deprecation(replace_x_with_y={"bw": "truncate"})
def smooth(self, *, sigma=None, truncate=None, inplace=False, mode=None, cval=None):
    """Smooths the tuning curve with a Gaussian kernel.

    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
    """
    if sigma is None:
        sigma = 0.1  # in units of extern
    if truncate is None:
        truncate = 4
    if mode is None:
        mode = "reflect"
    if cval is None:
        cval = 0.0

    ds = (self.bins[-1] - self.bins[0]) / self.n_bins
    sigma = sigma / ds

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

    if self.n_units > 1:
        out._ratemap = scipy.ndimage.filters.gaussian_filter(
            self.ratemap, sigma=(0, sigma), truncate=truncate, mode=mode, cval=cval
        )
    else:
        out._ratemap = scipy.ndimage.filters.gaussian_filter(
            self.ratemap, sigma=sigma, truncate=truncate, mode=mode, cval=cval
        )

    return out

spatial_information()

Compute the spatial information...

The specificity index examines the amount of information (in bits) that a single spike conveys about the animal's location (i.e., how well cell firing predicts the animal's location).The spatial information content of cell discharge was calculated using the formula: information content = \Sum P_i(R_i/R)log_2(R_i/R) where i is the bin number, P_i, is the probability for occupancy of bin i, R_i, is the mean firing rate for bin i, and R is the overall mean firing rate.

In order to account for the effects of low firing rates (with fewer spikes there is a tendency toward higher information content) or random bursts of firing, the spike firing time-series was randomly offset in time from the rat location time-series, and the information content was calculated. A distribution of the information content based on 100 such random shifts was obtained and was used to compute a standardized score (Zscore) of information content for that cell. While the distribution is not composed of independent samples, it was nominally normally distributed, and a Z value of 2.29 was chosen as a cut-off for significance (the equivalent of a one-tailed t-test with P = 0.01 under a normal distribution).

Reference(s)

Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L., and Skaggs, W. E. (1994). "Spatial information content and reliability of hippocampal CA1 neurons: effects of visual input", Hippocampus, 4(4), 410-421.

Parameters:

Name Type Description Default
Returns
required
si array of shape (n_units,)

spatial information (in bits) per unit

required
sparsity

sparsity (in percent) for each unit

required
Source code in nelpy/auxiliary/_tuningcurve.py
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
def spatial_information(self):
    """Compute the spatial information...

    The specificity index examines the amount of information
    (in bits) that a single spike conveys about the animal's
    location (i.e., how well cell firing predicts the animal's
    location).The spatial information content of cell discharge was
    calculated using the formula:
        information content = \Sum P_i(R_i/R)log_2(R_i/R)
    where i is the bin number, P_i, is the probability for occupancy
    of bin i, R_i, is the mean firing rate for bin i, and R is the
    overall mean firing rate.

    In order to account for the effects of low firing rates (with
    fewer spikes there is a tendency toward higher information
    content) or random bursts of firing, the spike firing
    time-series was randomly offset in time from the rat location
    time-series, and the information content was calculated. A
    distribution of the information content based on 100 such random
    shifts was obtained and was used to compute a standardized score
    (Zscore) of information content for that cell. While the
    distribution is not composed of independent samples, it was
    nominally normally distributed, and a Z value of 2.29 was chosen
    as a cut-off for significance (the equivalent of a one-tailed
    t-test with P = 0.01 under a normal distribution).

    Reference(s)
    ------------
    Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L.,
        and Skaggs, W. E. (1994). "Spatial information content and
        reliability of hippocampal CA1 neurons: effects of visual
        input", Hippocampus, 4(4), 410-421.

    Parameters
    ----------

    Returns
    -------
    si : array of shape (n_units,)
        spatial information (in bits) per unit
    sparsity: array of shape (n_units,)
        sparsity (in percent) for each unit
    """

    return utils.spatial_information(ratemap=self.ratemap, Pi=self.occupancy)

spatial_selectivity()

Compute the spatial selectivity...

Source code in nelpy/auxiliary/_tuningcurve.py
1255
1256
1257
def spatial_selectivity(self):
    """Compute the spatial selectivity..."""
    return utils.spatial_selectivity(ratemap=self.ratemap, Pi=self.occupancy)

spatial_sparsity()

Compute the firing sparsity...

Parameters:

Name Type Description Default
Returns
required
si array of shape (n_units,)

spatial information (in bits) per unit

required
sparsity

sparsity (in percent) for each unit

required
Source code in nelpy/auxiliary/_tuningcurve.py
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
def spatial_sparsity(self):
    """Compute the firing sparsity...

    Parameters
    ----------

    Returns
    -------
    si : array of shape (n_units,)
        spatial information (in bits) per unit
    sparsity: array of shape (n_units,)
        sparsity (in percent) for each unit
    """
    return utils.spatial_sparsity(ratemap=self.ratemap, Pi=self.occupancy)

TuningCurve2D

Tuning curves (2-dimensional) of multiple units.

Parameters:

Name Type Description Default
bst BinnedSpikeTrainArray

Binned spike train array for tuning curve estimation.

None
extern array - like

External correlates (e.g., position).

None
ratemap ndarray

Precomputed rate map.

None
sigma float

Standard deviation for Gaussian smoothing.

None
truncate float

Truncation parameter for smoothing.

None
ext_nx int

Number of bins in x-dimension.

None
ext_ny int

Number of bins in y-dimension.

None
transform_func callable

Function to transform external correlates.

None
minbgrate float

Minimum background firing rate.

None
ext_xmin float

Extent of the external correlates.

0
ext_xmax float

Extent of the external correlates.

0
ext_ymin float

Extent of the external correlates.

0
ext_ymax float

Extent of the external correlates.

0
extlabels list

Labels for external correlates.

None
min_duration float

Minimum duration for occupancy.

None
unit_ids list

Unit IDs.

None
unit_labels list

Unit labels.

None
unit_tags list

Unit tags.

None
label str

Label for the tuning curve.

None
empty bool

If True, create an empty TuningCurve2D.

False

Attributes:

Name Type Description
ratemap ndarray

The 2D rate map.

occupancy ndarray

Occupancy map.

unit_ids list

Unit IDs.

unit_labels list

Unit labels.

unit_tags list

Unit tags.

label str

Label for the tuning curve.

mask ndarray

Mask for valid regions.

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

    Parameters
    ----------
    bst : BinnedSpikeTrainArray, optional
        Binned spike train array for tuning curve estimation.
    extern : array-like, optional
        External correlates (e.g., position).
    ratemap : np.ndarray, optional
        Precomputed rate map.
    sigma : float, optional
        Standard deviation for Gaussian smoothing.
    truncate : float, optional
        Truncation parameter for smoothing.
    ext_nx : int, optional
        Number of bins in x-dimension.
    ext_ny : int, optional
        Number of bins in y-dimension.
    transform_func : callable, optional
        Function to transform external correlates.
    minbgrate : float, optional
        Minimum background firing rate.
    ext_xmin, ext_xmax, ext_ymin, ext_ymax : float, optional
        Extent of the external correlates.
    extlabels : list, optional
        Labels for external correlates.
    min_duration : float, optional
        Minimum duration for occupancy.
    unit_ids : list, optional
        Unit IDs.
    unit_labels : list, optional
        Unit labels.
    unit_tags : list, optional
        Unit tags.
    label : str, optional
        Label for the tuning curve.
    empty : bool, optional
        If True, create an empty TuningCurve2D.

    Attributes
    ----------
    ratemap : np.ndarray
        The 2D rate map.
    occupancy : np.ndarray
        Occupancy map.
    unit_ids : list
        Unit IDs.
    unit_labels : list
        Unit labels.
    unit_tags : list
        Unit tags.
    label : str
        Label for the tuning curve.
    mask : np.ndarray
        Mask for valid regions.
    """

    __attributes__ = [
        "_ratemap",
        "_occupancy",
        "_unit_ids",
        "_unit_labels",
        "_unit_tags",
        "_label",
        "_mask",
    ]

    @keyword_deprecation(replace_x_with_y={"bw": "truncate"})
    def __init__(
        self,
        *,
        bst=None,
        extern=None,
        ratemap=None,
        sigma=None,
        truncate=None,
        ext_nx=None,
        ext_ny=None,
        transform_func=None,
        minbgrate=None,
        ext_xmin=0,
        ext_ymin=0,
        ext_xmax=1,
        ext_ymax=1,
        extlabels=None,
        min_duration=None,
        unit_ids=None,
        unit_labels=None,
        unit_tags=None,
        label=None,
        empty=False,
    ):
        """

        NOTE: tuning curves in 2D have shapes (n_units, ny, nx) so that
        we can plot them in an intuitive manner

        If sigma is nonzero, then smoothing is applied.

        We always require bst and extern, and then some combination of
            (1) bin edges, transform_func*
            (2) n_extern, transform_func*
            (3) n_extern, x_min, x_max, transform_func*

            transform_func operates on extern and returns a value that
            TuninCurve2D can interpret. If no transform is specified, the
            identity operator is assumed.

        TODO: ext_xmin and ext_xmax (and same for y) should be inferred from
        extern if not passed in explicitly.

        e.g.
            ext_xmin, ext_xmax = np.floor(pos[:,0].min()/10)*10, np.ceil(pos[:,0].max()/10)*10
            ext_ymin, ext_ymax = np.floor(pos[:,1].min()/10)*10, np.ceil(pos[:,1].max()/10)*10

        TODO: mask should be learned during constructor, or additionally
        after-the-fact. If a mask is present, then smoothing should be applied
        while respecting this mask. Similarly, decoding MAY be altered by
        finding the closest point WITHIN THE MASK after doing mean decoding?
        This way, if there's an outlier pulling us off of the track, we may
        expect decoding accuracy to be improved.
        """
        # TODO: input validation
        if not empty:
            if ratemap is None:
                assert bst is not None, (
                    "bst must be specified or ratemap must be specified!"
                )
                assert extern is not None, (
                    "extern must be specified or ratemap must be specified!"
                )
            else:
                assert bst is None, "ratemap and bst cannot both be specified!"
                assert extern is None, "ratemap and extern cannot both be specified!"

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

        if ratemap is not None:
            for attr in self.__attributes__:
                exec("self." + attr + " = None")
            self._init_from_ratemap(
                ratemap=ratemap,
                ext_xmin=ext_xmin,
                ext_xmax=ext_xmax,
                ext_ymin=ext_ymin,
                ext_ymax=ext_ymax,
                extlabels=extlabels,
                unit_ids=unit_ids,
                unit_labels=unit_labels,
                unit_tags=unit_tags,
                label=label,
            )
            return

        self._mask = None  # TODO: change this when we can learn a mask in __init__!
        self._bst = bst
        self._extern = extern

        if minbgrate is None:
            minbgrate = 0.01  # Hz minimum background firing rate

        if ext_nx is not None:
            if ext_xmin is not None and ext_xmax is not None:
                self._xbins = np.linspace(ext_xmin, ext_xmax, ext_nx + 1)
            else:
                raise NotImplementedError
        else:
            raise NotImplementedError

        if ext_ny is not None:
            if ext_ymin is not None and ext_ymax is not None:
                self._ybins = np.linspace(ext_ymin, ext_ymax, ext_ny + 1)
            else:
                raise NotImplementedError
        else:
            raise NotImplementedError

        if min_duration is None:
            min_duration = 0

        self._min_duration = min_duration
        self._unit_ids = bst.unit_ids
        self._unit_labels = bst.unit_labels
        self._unit_tags = bst.unit_tags  # no input validation yet
        self.label = label

        if transform_func is None:
            self.trans_func = self._trans_func
        else:
            self.trans_func = transform_func

        # compute occupancy
        self._occupancy = self._compute_occupancy()
        # compute ratemap (in Hz)
        self._ratemap = self._compute_ratemap()
        # normalize firing rate by occupancy
        self._ratemap = self._normalize_firing_rate_by_occupancy()
        # enforce minimum background firing rate
        self._ratemap[self._ratemap < minbgrate] = (
            minbgrate  # background firing rate of 0.01 Hz
        )

        # TODO: support 2D sigma
        if sigma is not None:
            if sigma > 0:
                self.smooth(sigma=sigma, truncate=truncate, inplace=True)

        # optionally detach _bst and _extern to save space when pickling, for example
        self._detach()

    def spatial_information(self):
        """Compute the spatial information and firing sparsity...

        The specificity index examines the amount of information
        (in bits) that a single spike conveys about the animal's
        location (i.e., how well cell firing predicts the animal's
        location).The spatial information content of cell discharge was
        calculated using the formula:
            information content = \\Sum P_i(R_i/R)log_2(R_i/R)
        where i is the bin number, P_i, is the probability for occupancy
        of bin i, R_i, is the mean firing rate for bin i, and R is the
        overall mean firing rate.

        In order to account for the effects of low firing rates (with
        fewer spikes there is a tendency toward higher information
        content) or random bursts of firing, the spike firing
        time-series was randomly offset in time from the rat location
        time-series, and the information content was calculated. A
        distribution of the information content based on 100 such random
        shifts was obtained and was used to compute a standardized score
        (Zscore) of information content for that cell. While the
        distribution is not composed of independent samples, it was
        nominally normally distributed, and a Z value of 2.29 was chosen
        as a cut-off for significance (the equivalent of a one-tailed
        t-test with P = 0.01 under a normal distribution).

        Reference(s)
        ------------
        Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L.,
            and Skaggs, W. E. (1994). "Spatial information content and
            reliability of hippocampal CA1 neurons: effects of visual
            input", Hippocampus, 4(4), 410-421.

        Parameters
        ----------

        Returns
        -------
        si : array of shape (n_units,)
            spatial information (in bits) per spike
        """

        return utils.spatial_information(ratemap=self.ratemap, Pi=self.occupancy)

    def information_rate(self):
        """Compute the information rate..."""
        return utils.information_rate(ratemap=self.ratemap, Pi=self.occupancy)

    def spatial_selectivity(self):
        """Compute the spatial selectivity..."""
        return utils.spatial_selectivity(ratemap=self.ratemap, Pi=self.occupancy)

    def spatial_sparsity(self):
        """Compute the spatial information and firing sparsity...

        The specificity index examines the amount of information
        (in bits) that a single spike conveys about the animal's
        location (i.e., how well cell firing predicts the animal's
        location).The spatial information content of cell discharge was
        calculated using the formula:
            information content = \Sum P_i(R_i/R)log_2(R_i/R)
        where i is the bin number, P_i, is the probability for occupancy
        of bin i, R_i, is the mean firing rate for bin i, and R is the
        overall mean firing rate.

        In order to account for the effects of low firing rates (with
        fewer spikes there is a tendency toward higher information
        content) or random bursts of firing, the spike firing
        time-series was randomly offset in time from the rat location
        time-series, and the information content was calculated. A
        distribution of the information content based on 100 such random
        shifts was obtained and was used to compute a standardized score
        (Zscore) of information content for that cell. While the
        distribution is not composed of independent samples, it was
        nominally normally distributed, and a Z value of 2.29 was chosen
        as a cut-off for significance (the equivalent of a one-tailed
        t-test with P = 0.01 under a normal distribution).

        Reference(s)
        ------------
        Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L.,
            and Skaggs, W. E. (1994). "Spatial information content and
            reliability of hippocampal CA1 neurons: effects of visual
            input", Hippocampus, 4(4), 410-421.

        Parameters
        ----------

        Returns
        -------
        si : array of shape (n_units,)
            spatial information (in bits) per unit
        sparsity: array of shape (n_units,)
            sparsity (in percent) for each unit
        """
        return utils.spatial_sparsity(ratemap=self.ratemap, Pi=self.occupancy)

    def _initialize_mask_from_extern(self, extern):
        """Attached a mask from extern.
        TODO: improve docstring, add example.
        Typically extern is an AnalogSignalArray or a PositionArray.
        """
        xpos, ypos = extern.asarray().yvals
        mask_x = np.digitize(xpos, self._xbins, right=True) - 1  # spatial bin numbers
        mask_y = np.digitize(ypos, self._ybins, right=True) - 1  # spatial bin numbers

        mask = np.empty((self.n_xbins, self.n_xbins))
        mask[:] = np.nan
        mask[mask_x, mask_y] = 1

        self._mask_x = mask_x  # may not be useful or necessary to store?
        self._mask_y = mask_y  # may not be useful or necessary to store?
        self._mask = mask

    def __add__(self, other):
        out = copy.copy(self)

        if isinstance(other, numbers.Number):
            out._ratemap = out.ratemap + other
        elif isinstance(other, TuningCurve2D):
            # TODO: this should merge two TuningCurve2D objects
            raise NotImplementedError
        else:
            raise TypeError(
                "unsupported operand type(s) for +: 'TuningCurve2D' and '{}'".format(
                    str(type(other))
                )
            )
        return out

    def __sub__(self, other):
        out = copy.copy(self)
        out._ratemap = out.ratemap - other
        return out

    def __mul__(self, other):
        """overloaded * operator."""
        out = copy.copy(self)
        out._ratemap = out.ratemap * other
        return out

    def __rmul__(self, other):
        return self * other

    def __truediv__(self, other):
        """overloaded / operator."""
        out = copy.copy(self)
        out._ratemap = out.ratemap / other
        return out

    def _init_from_ratemap(
        self,
        ratemap,
        occupancy=None,
        ext_xmin=0,
        ext_xmax=1,
        ext_ymin=0,
        ext_ymax=1,
        extlabels=None,
        unit_ids=None,
        unit_labels=None,
        unit_tags=None,
        label=None,
    ):
        """Initialize a TuningCurve2D object from a ratemap.

        Parameters
        ----------
        ratemap : array
            Array of shape (n_units, ext_nx, ext_ny)

        Returns
        -------

        """
        n_units, ext_nx, ext_ny = ratemap.shape

        if occupancy is None:
            # assume uniform occupancy
            self._occupancy = np.ones((ext_nx, ext_ny))

        if ext_xmin is None:
            ext_xmin = 0
        if ext_xmax is None:
            ext_xmax = ext_xmin + 1

        if ext_ymin is None:
            ext_ymin = 0
        if ext_ymax is None:
            ext_ymax = ext_ymin + 1

        self._xbins = np.linspace(ext_xmin, ext_xmax, ext_nx + 1)
        self._ybins = np.linspace(ext_ymin, ext_ymax, ext_ny + 1)
        self._ratemap = ratemap

        # inherit unit IDs if available, otherwise initialize to default
        if unit_ids is None:
            unit_ids = list(range(1, n_units + 1))

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

        # if unit_labels is empty, default to unit_ids
        if unit_labels is None:
            unit_labels = unit_ids

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

        self._unit_ids = unit_ids
        self._unit_labels = unit_labels
        self._unit_tags = unit_tags  # no input validation yet
        if label is not None:
            self.label = label

        return self

    def max(self, *, axis=None):
        """Returns the mean of firing rate (in Hz).
        Parameters
        ----------
        axis : int, optional
            When axis is None, the global max firing rate is returned.
            When axis is 0, the max firing rates across units, as a
            function of the external correlate (e.g. position) are
            returned.
            When axis is 1, the max firing rate for each unit is
            returned.
        Returns
        -------
        max :
        """
        if (axis is None) | (axis == 0):
            maxes = np.max(self.ratemap, axis=axis)
        elif axis == 1:
            maxes = [
                self.ratemap[unit_i, :, :].max()
                for unit_i in range(self.ratemap.shape[0])
            ]

        return maxes

    def min(self, *, axis=None):
        """Returns the min of firing rate (in Hz).
        Parameters
        ----------
        axis : int, optional
            When axis is None, the global min firing rate is returned.
            When axis is 0, the min firing rates across units, as a
            function of the external correlate (e.g. position) are
            returned.
            When axis is 1, the min firing rate for each unit is
            returned.
        Returns
        -------
        min :
        """

        if (axis is None) | (axis == 0):
            mins = np.min(self.ratemap, axis=axis)
        elif axis == 1:
            mins = [
                self.ratemap[unit_i, :, :].min()
                for unit_i in range(self.ratemap.shape[0])
            ]

        return mins

    def mean(self, *, axis=None):
        """Returns the mean of firing rate (in Hz).
        Parameters
        ----------
        axis : int, optional
            When axis is None, the global mean firing rate is returned.
            When axis is 0, the mean firing rates across units, as a
            function of the external correlate (e.g. position) are
            returned.
            When axis is 1, the mean firing rate for each unit is
            returned.
        Returns
        -------
        mean :
        """

        if (axis is None) | (axis == 0):
            means = np.mean(self.ratemap, axis=axis)
        elif axis == 1:
            means = [
                self.ratemap[unit_i, :, :].mean()
                for unit_i in range(self.ratemap.shape[0])
            ]

        return means

    def std(self, *, axis=None):
        """Returns the std of firing rate (in Hz).
        Parameters
        ----------
        axis : int, optional
            When axis is None, the global std firing rate is returned.
            When axis is 0, the std firing rates across units, as a
            function of the external correlate (e.g. position) are
            returned.
            When axis is 1, the std firing rate for each unit is
            returned.
        Returns
        -------
        std :
        """

        if (axis is None) | (axis == 0):
            stds = np.std(self.ratemap, axis=axis)
        elif axis == 1:
            stds = [
                self.ratemap[unit_i, :, :].std()
                for unit_i in range(self.ratemap.shape[0])
            ]

        return stds

    def _detach(self):
        """Detach bst and extern from tuning curve."""
        self._bst = None
        self._extern = None

    @property
    def mask(self):
        """(n_xbins, n_ybins) Mask for tuning curve."""
        return self._mask

    @property
    def n_bins(self):
        """(int) Number of external correlates (bins)."""
        return self.n_xbins * self.n_ybins

    @property
    def n_xbins(self):
        """(int) Number of external correlates (bins)."""
        return len(self.xbins) - 1

    @property
    def n_ybins(self):
        """(int) Number of external correlates (bins)."""
        return len(self.ybins) - 1

    @property
    def xbins(self):
        """External correlate bins."""
        return self._xbins

    @property
    def ybins(self):
        """External correlate bins."""
        return self._ybins

    @property
    def xbin_centers(self):
        """External correlate bin centers."""
        return (self.xbins + (self.xbins[1] - self.xbins[0]) / 2)[:-1]

    @property
    def ybin_centers(self):
        """External correlate bin centers."""
        return (self.ybins + (self.ybins[1] - self.ybins[0]) / 2)[:-1]

    @property
    def bin_centers(self):
        return tuple([self.xbin_centers, self.ybin_centers])

    @property
    def bins(self):
        """External correlate bins."""
        return (self.xbins, self.ybins)

    def _trans_func(self, extern, at):
        """Default transform function to map extern into numerical bins.

        Assumes first signal is x-dim, second is y-dim.
        """

        _, ext = extern.asarray(at=at)
        x, y = ext[0, :], ext[1, :]

        return np.atleast_1d(x), np.atleast_1d(y)

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

        Accepts integers, slices, and lists"""

        idx = [ii for ii in idx]
        if len(idx) == 1 and not isinstance(idx[0], int):
            idx = idx[0]
        if isinstance(idx, tuple):
            idx = [ii for ii in idx]

        if self.isempty:
            return self
        try:
            out = copy.copy(self)
            out._ratemap = self.ratemap[idx, :]
            out._unit_ids = (np.asanyarray(out._unit_ids)[idx]).tolist()
            out._unit_labels = (np.asanyarray(out._unit_labels)[idx]).tolist()
            return out
        except Exception:
            raise TypeError("unsupported subsctipting type {}".format(type(idx)))

    def _compute_occupancy(self):
        """ """

        # Make sure that self._bst_centers fall within not only the support
        # of extern, but also within the extreme sample times; otherwise,
        # interpolation will yield NaNs at the extremes. Indeed, when we have
        # sample times within a support epoch, we can assume that the signal
        # stayed roughly constant for that one sample duration.

        if self._bst._bin_centers[0] < self._extern.time[0]:
            self._extern = copy.copy(self._extern)
            self._extern.time[0] = self._bst._bin_centers[0]
            self._extern._interp = None
            # raise ValueError('interpolated sample requested before first sample of extern!')
        if self._bst._bin_centers[-1] > self._extern.time[-1]:
            self._extern = copy.copy(self._extern)
            self._extern.time[-1] = self._bst._bin_centers[-1]
            self._extern._interp = None
            # raise ValueError('interpolated sample requested after last sample of extern!')

        x, y = self.trans_func(self._extern, at=self._bst.bin_centers)

        xmin = self.xbins[0]
        xmax = self.xbins[-1]
        ymin = self.ybins[0]
        ymax = self.ybins[-1]

        occupancy, _, _ = np.histogram2d(
            x, y, bins=[self.xbins, self.ybins], range=([[xmin, xmax], [ymin, ymax]])
        )

        return occupancy

    def _compute_ratemap(self, min_duration=None):
        """

        min_duration is the min duration in seconds for a bin to be
        considered 'valid'; if too few observations were made, then the
        firing rate is kept at an estimate of 0. If min_duration == 0,
        then all the spikes are used.
        """

        if min_duration is None:
            min_duration = self._min_duration

        x, y = self.trans_func(self._extern, at=self._bst.bin_centers)

        ext_bin_idx_x = np.squeeze(np.digitize(x, self.xbins, right=True))
        ext_bin_idx_y = np.squeeze(np.digitize(y, self.ybins, right=True))

        # make sure that all the events fit between extmin and extmax:
        # TODO: this might rather be a warning, but it's a pretty serious warning...
        if ext_bin_idx_x.max() > self.n_xbins:
            raise ValueError("ext values greater than 'ext_xmax'")
        if ext_bin_idx_x.min() == 0:
            raise ValueError("ext values less than 'ext_xmin'")
        if ext_bin_idx_y.max() > self.n_ybins:
            raise ValueError("ext values greater than 'ext_ymax'")
        if ext_bin_idx_y.min() == 0:
            raise ValueError("ext values less than 'ext_ymin'")

        ratemap = np.zeros((self.n_units, self.n_xbins, self.n_ybins))

        for tt, (bidxx, bidxy) in enumerate(zip(ext_bin_idx_x, ext_bin_idx_y)):
            ratemap[:, bidxx - 1, bidxy - 1] += self._bst.data[:, tt]

        # apply minimum observation duration
        for uu in range(self.n_units):
            ratemap[uu][self.occupancy * self._bst.ds < min_duration] = 0

        return ratemap / self._bst.ds

    def normalize(self, inplace=False):
        """Normalize firing rates. For visualization."""

        raise NotImplementedError

        if not inplace:
            out = copy.deepcopy(self)
        else:
            out = self
        if self.n_units > 1:
            per_unit_max = np.max(out.ratemap, axis=1)[..., np.newaxis]
            out._ratemap = self.ratemap / np.tile(per_unit_max, (1, out.n_bins))
        else:
            per_unit_max = np.max(out.ratemap)
            out._ratemap = self.ratemap / np.tile(per_unit_max, out.n_bins)
        return out

    def _normalize_firing_rate_by_occupancy(self):
        # normalize spike counts by occupancy:
        denom = np.tile(self.occupancy, (self.n_units, 1, 1))
        denom[denom == 0] = 1
        ratemap = self.ratemap / denom
        return ratemap

    @property
    def is2d(self):
        return True

    @property
    def occupancy(self):
        return self._occupancy

    @property
    def n_units(self):
        """(int) The number of units."""
        try:
            return len(self._unit_ids)
        except TypeError:  # when unit_ids is an integer
            return 1
        except AttributeError:
            return 0

    @property
    def shape(self):
        """(tuple) The shape of the TuningCurve2D ratemap."""
        if self.isempty:
            return (self.n_units, 0, 0)
        if len(self.ratemap.shape) == 1:
            return (self.ratemap.shape[0], 1, 1)
        return self.ratemap.shape

    def __repr__(self):
        address_str = " at " + str(hex(id(self)))
        if self.isempty:
            return "<empty TuningCurve2D" + address_str + ">"
        shapestr = " with shape (%s, %s, %s)" % (
            self.shape[0],
            self.shape[1],
            self.shape[2],
        )
        return "<TuningCurve2D%s>%s" % (address_str, shapestr)

    @property
    def isempty(self):
        """(bool) True if TuningCurve1D is empty"""
        try:
            return len(self.ratemap) == 0
        except TypeError:  # TypeError should happen if ratemap = []
            return True

    @property
    def ratemap(self):
        return self._ratemap

    def __len__(self):
        return self.n_units

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

    def __next__(self):
        """TuningCurve2D iterator advancer."""
        index = self._index
        if index > self.n_units - 1:
            raise StopIteration
        out = copy.copy(self)
        out._ratemap = self.ratemap[index, :]
        out._unit_ids = self.unit_ids[index]
        out._unit_labels = self.unit_labels[index]
        self._index += 1
        return out

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

        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
        """
        if sigma is None:
            sigma = 0.1  # in units of extern
        if truncate is None:
            truncate = 4
        if mode is None:
            mode = "reflect"
        if cval is None:
            cval = 0.0

        ds_x = (self.xbins[-1] - self.xbins[0]) / self.n_xbins
        ds_y = (self.ybins[-1] - self.ybins[0]) / self.n_ybins
        sigma_x = sigma / ds_x
        sigma_y = sigma / ds_y

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

        if self.mask is None:
            if (self.n_units > 1) | (self.ratemap.shape[0] > 1):
                out._ratemap = scipy.ndimage.filters.gaussian_filter(
                    self.ratemap,
                    sigma=(0, sigma_x, sigma_y),
                    truncate=truncate,
                    mode=mode,
                    cval=cval,
                )
            elif self.ratemap.shape[0] == 1:
                out._ratemap[0, :, :] = scipy.ndimage.filters.gaussian_filter(
                    self.ratemap[0, :, :],
                    sigma=(sigma_x, sigma_y),
                    truncate=truncate,
                    mode=mode,
                    cval=cval,
                )
            else:
                raise ValueError("ratemap has an unexpected shape")
        else:  # we have a mask!
            # smooth, dealing properly with NANs
            # NB! see https://stackoverflow.com/questions/18697532/gaussian-filtering-a-image-with-nan-in-python

            masked_ratemap = self.ratemap.copy() * self.mask
            V = masked_ratemap.copy()
            V[masked_ratemap != masked_ratemap] = 0
            W = 0 * masked_ratemap.copy() + 1
            W[masked_ratemap != masked_ratemap] = 0

            if (self.n_units > 1) | (self.ratemap.shape[0] > 1):
                VV = scipy.ndimage.filters.gaussian_filter(
                    V,
                    sigma=(0, sigma_x, sigma_y),
                    truncate=truncate,
                    mode=mode,
                    cval=cval,
                )
                WW = scipy.ndimage.filters.gaussian_filter(
                    W,
                    sigma=(0, sigma_x, sigma_y),
                    truncate=truncate,
                    mode=mode,
                    cval=cval,
                )
                Z = VV / WW
                out._ratemap = Z * self.mask
            else:
                VV = scipy.ndimage.filters.gaussian_filter(
                    V, sigma=(sigma_x, sigma_y), truncate=truncate, mode=mode, cval=cval
                )
                WW = scipy.ndimage.filters.gaussian_filter(
                    W, sigma=(sigma_x, sigma_y), truncate=truncate, mode=mode, cval=cval
                )
                Z = VV / WW
                out._ratemap = Z * self.mask

        return out

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

        neworder must be list-like, of size (n_units,) and in terms of
        unit_ids

        Return
        ------
        out : reordered TuningCurve2D
        """

        def swap_units(arr, frm, to):
            """swap 'units' of a 3D np.array"""
            arr[[frm, to], :, :] = arr[[to, frm], :, :]

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

        # unit_ids = list(self.unit_ids)

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

        oldorder = list(range(len(neworder)))
        for oi, ni in enumerate(neworder):
            frm = oldorder.index(ni)
            to = oi
            swap_units(out._ratemap, frm, to)
            out._unit_ids[frm], out._unit_ids[to] = (
                out._unit_ids[to],
                out._unit_ids[frm],
            )
            out._unit_labels[frm], out._unit_labels[to] = (
                out._unit_labels[to],
                out._unit_labels[frm],
            )
            # TODO: re-build unit tags (tag system not yet implemented)
            oldorder[frm], oldorder[to] = oldorder[to], oldorder[frm]

        return out

    @property
    def unit_ids(self):
        """Unit IDs contained in the SpikeTrain."""
        return list(self._unit_ids)

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

    @property
    def unit_labels(self):
        """Labels corresponding to units contained in the SpikeTrain."""
        if self._unit_labels is None:
            warnings.warn("unit labels have not yet been specified")
        return self._unit_labels

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

    @property
    def unit_tags(self):
        """Tags corresponding to units contained in the SpikeTrain"""
        if self._unit_tags is None:
            warnings.warn("unit tags have not yet been specified")
        return self._unit_tags

    @property
    def label(self):
        """Label pertaining to the source of the spike train."""
        if self._label is None:
            warnings.warn("label has not yet been specified")
        return self._label

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

bins property

External correlate bins.

isempty property

(bool) True if TuningCurve1D is empty

label property writable

Label pertaining to the source of the spike train.

mask property

(n_xbins, n_ybins) Mask for tuning curve.

n_bins property

(int) Number of external correlates (bins).

n_units property

(int) The number of units.

n_xbins property

(int) Number of external correlates (bins).

n_ybins property

(int) Number of external correlates (bins).

shape property

(tuple) The shape of the TuningCurve2D ratemap.

unit_ids property writable

Unit IDs contained in the SpikeTrain.

unit_labels property writable

Labels corresponding to units contained in the SpikeTrain.

unit_tags property

Tags corresponding to units contained in the SpikeTrain

xbin_centers property

External correlate bin centers.

xbins property

External correlate bins.

ybin_centers property

External correlate bin centers.

ybins property

External correlate bins.

information_rate()

Compute the information rate...

Source code in nelpy/auxiliary/_tuningcurve.py
298
299
300
def information_rate(self):
    """Compute the information rate..."""
    return utils.information_rate(ratemap=self.ratemap, Pi=self.occupancy)

max(*, axis=None)

Returns the mean of firing rate (in Hz).

Parameters:

Name Type Description Default
axis int

When axis is None, the global max firing rate is returned. When axis is 0, the max firing rates across units, as a function of the external correlate (e.g. position) are returned. When axis is 1, the max firing rate for each unit is returned.

None

Returns:

Name Type Description
max
Source code in nelpy/auxiliary/_tuningcurve.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
def max(self, *, axis=None):
    """Returns the mean of firing rate (in Hz).
    Parameters
    ----------
    axis : int, optional
        When axis is None, the global max firing rate is returned.
        When axis is 0, the max firing rates across units, as a
        function of the external correlate (e.g. position) are
        returned.
        When axis is 1, the max firing rate for each unit is
        returned.
    Returns
    -------
    max :
    """
    if (axis is None) | (axis == 0):
        maxes = np.max(self.ratemap, axis=axis)
    elif axis == 1:
        maxes = [
            self.ratemap[unit_i, :, :].max()
            for unit_i in range(self.ratemap.shape[0])
        ]

    return maxes

mean(*, axis=None)

Returns the mean of firing rate (in Hz).

Parameters:

Name Type Description Default
axis int

When axis is None, the global mean firing rate is returned. When axis is 0, the mean firing rates across units, as a function of the external correlate (e.g. position) are returned. When axis is 1, the mean firing rate for each unit is returned.

None

Returns:

Name Type Description
mean
Source code in nelpy/auxiliary/_tuningcurve.py
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
def mean(self, *, axis=None):
    """Returns the mean of firing rate (in Hz).
    Parameters
    ----------
    axis : int, optional
        When axis is None, the global mean firing rate is returned.
        When axis is 0, the mean firing rates across units, as a
        function of the external correlate (e.g. position) are
        returned.
        When axis is 1, the mean firing rate for each unit is
        returned.
    Returns
    -------
    mean :
    """

    if (axis is None) | (axis == 0):
        means = np.mean(self.ratemap, axis=axis)
    elif axis == 1:
        means = [
            self.ratemap[unit_i, :, :].mean()
            for unit_i in range(self.ratemap.shape[0])
        ]

    return means

min(*, axis=None)

Returns the min of firing rate (in Hz).

Parameters:

Name Type Description Default
axis int

When axis is None, the global min firing rate is returned. When axis is 0, the min firing rates across units, as a function of the external correlate (e.g. position) are returned. When axis is 1, the min firing rate for each unit is returned.

None

Returns:

Name Type Description
min
Source code in nelpy/auxiliary/_tuningcurve.py
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
def min(self, *, axis=None):
    """Returns the min of firing rate (in Hz).
    Parameters
    ----------
    axis : int, optional
        When axis is None, the global min firing rate is returned.
        When axis is 0, the min firing rates across units, as a
        function of the external correlate (e.g. position) are
        returned.
        When axis is 1, the min firing rate for each unit is
        returned.
    Returns
    -------
    min :
    """

    if (axis is None) | (axis == 0):
        mins = np.min(self.ratemap, axis=axis)
    elif axis == 1:
        mins = [
            self.ratemap[unit_i, :, :].min()
            for unit_i in range(self.ratemap.shape[0])
        ]

    return mins

normalize(inplace=False)

Normalize firing rates. For visualization.

Source code in nelpy/auxiliary/_tuningcurve.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
def normalize(self, inplace=False):
    """Normalize firing rates. For visualization."""

    raise NotImplementedError

    if not inplace:
        out = copy.deepcopy(self)
    else:
        out = self
    if self.n_units > 1:
        per_unit_max = np.max(out.ratemap, axis=1)[..., np.newaxis]
        out._ratemap = self.ratemap / np.tile(per_unit_max, (1, out.n_bins))
    else:
        per_unit_max = np.max(out.ratemap)
        out._ratemap = self.ratemap / np.tile(per_unit_max, out.n_bins)
    return out

reorder_units_by_ids(neworder, *, inplace=False)

Reorder units according to a specified order.

neworder must be list-like, of size (n_units,) and in terms of unit_ids

Return

out : reordered TuningCurve2D

Source code in nelpy/auxiliary/_tuningcurve.py
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
def reorder_units_by_ids(self, neworder, *, inplace=False):
    """Reorder units according to a specified order.

    neworder must be list-like, of size (n_units,) and in terms of
    unit_ids

    Return
    ------
    out : reordered TuningCurve2D
    """

    def swap_units(arr, frm, to):
        """swap 'units' of a 3D np.array"""
        arr[[frm, to], :, :] = arr[[to, frm], :, :]

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

    # unit_ids = list(self.unit_ids)

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

    oldorder = list(range(len(neworder)))
    for oi, ni in enumerate(neworder):
        frm = oldorder.index(ni)
        to = oi
        swap_units(out._ratemap, frm, to)
        out._unit_ids[frm], out._unit_ids[to] = (
            out._unit_ids[to],
            out._unit_ids[frm],
        )
        out._unit_labels[frm], out._unit_labels[to] = (
            out._unit_labels[to],
            out._unit_labels[frm],
        )
        # TODO: re-build unit tags (tag system not yet implemented)
        oldorder[frm], oldorder[to] = oldorder[to], oldorder[frm]

    return out

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

Smooths the tuning curve with a Gaussian kernel.

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

Source code in nelpy/auxiliary/_tuningcurve.py
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
@keyword_deprecation(replace_x_with_y={"bw": "truncate"})
def smooth(self, *, sigma=None, truncate=None, inplace=False, mode=None, cval=None):
    """Smooths the tuning curve with a Gaussian kernel.

    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
    """
    if sigma is None:
        sigma = 0.1  # in units of extern
    if truncate is None:
        truncate = 4
    if mode is None:
        mode = "reflect"
    if cval is None:
        cval = 0.0

    ds_x = (self.xbins[-1] - self.xbins[0]) / self.n_xbins
    ds_y = (self.ybins[-1] - self.ybins[0]) / self.n_ybins
    sigma_x = sigma / ds_x
    sigma_y = sigma / ds_y

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

    if self.mask is None:
        if (self.n_units > 1) | (self.ratemap.shape[0] > 1):
            out._ratemap = scipy.ndimage.filters.gaussian_filter(
                self.ratemap,
                sigma=(0, sigma_x, sigma_y),
                truncate=truncate,
                mode=mode,
                cval=cval,
            )
        elif self.ratemap.shape[0] == 1:
            out._ratemap[0, :, :] = scipy.ndimage.filters.gaussian_filter(
                self.ratemap[0, :, :],
                sigma=(sigma_x, sigma_y),
                truncate=truncate,
                mode=mode,
                cval=cval,
            )
        else:
            raise ValueError("ratemap has an unexpected shape")
    else:  # we have a mask!
        # smooth, dealing properly with NANs
        # NB! see https://stackoverflow.com/questions/18697532/gaussian-filtering-a-image-with-nan-in-python

        masked_ratemap = self.ratemap.copy() * self.mask
        V = masked_ratemap.copy()
        V[masked_ratemap != masked_ratemap] = 0
        W = 0 * masked_ratemap.copy() + 1
        W[masked_ratemap != masked_ratemap] = 0

        if (self.n_units > 1) | (self.ratemap.shape[0] > 1):
            VV = scipy.ndimage.filters.gaussian_filter(
                V,
                sigma=(0, sigma_x, sigma_y),
                truncate=truncate,
                mode=mode,
                cval=cval,
            )
            WW = scipy.ndimage.filters.gaussian_filter(
                W,
                sigma=(0, sigma_x, sigma_y),
                truncate=truncate,
                mode=mode,
                cval=cval,
            )
            Z = VV / WW
            out._ratemap = Z * self.mask
        else:
            VV = scipy.ndimage.filters.gaussian_filter(
                V, sigma=(sigma_x, sigma_y), truncate=truncate, mode=mode, cval=cval
            )
            WW = scipy.ndimage.filters.gaussian_filter(
                W, sigma=(sigma_x, sigma_y), truncate=truncate, mode=mode, cval=cval
            )
            Z = VV / WW
            out._ratemap = Z * self.mask

    return out

spatial_information()

Compute the spatial information and firing sparsity...

The specificity index examines the amount of information (in bits) that a single spike conveys about the animal's location (i.e., how well cell firing predicts the animal's location).The spatial information content of cell discharge was calculated using the formula: information content = \Sum P_i(R_i/R)log_2(R_i/R) where i is the bin number, P_i, is the probability for occupancy of bin i, R_i, is the mean firing rate for bin i, and R is the overall mean firing rate.

In order to account for the effects of low firing rates (with fewer spikes there is a tendency toward higher information content) or random bursts of firing, the spike firing time-series was randomly offset in time from the rat location time-series, and the information content was calculated. A distribution of the information content based on 100 such random shifts was obtained and was used to compute a standardized score (Zscore) of information content for that cell. While the distribution is not composed of independent samples, it was nominally normally distributed, and a Z value of 2.29 was chosen as a cut-off for significance (the equivalent of a one-tailed t-test with P = 0.01 under a normal distribution).

Reference(s)

Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L., and Skaggs, W. E. (1994). "Spatial information content and reliability of hippocampal CA1 neurons: effects of visual input", Hippocampus, 4(4), 410-421.

Parameters:

Name Type Description Default
Returns
required
si array of shape (n_units,)

spatial information (in bits) per spike

required
Source code in nelpy/auxiliary/_tuningcurve.py
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
def spatial_information(self):
    """Compute the spatial information and firing sparsity...

    The specificity index examines the amount of information
    (in bits) that a single spike conveys about the animal's
    location (i.e., how well cell firing predicts the animal's
    location).The spatial information content of cell discharge was
    calculated using the formula:
        information content = \\Sum P_i(R_i/R)log_2(R_i/R)
    where i is the bin number, P_i, is the probability for occupancy
    of bin i, R_i, is the mean firing rate for bin i, and R is the
    overall mean firing rate.

    In order to account for the effects of low firing rates (with
    fewer spikes there is a tendency toward higher information
    content) or random bursts of firing, the spike firing
    time-series was randomly offset in time from the rat location
    time-series, and the information content was calculated. A
    distribution of the information content based on 100 such random
    shifts was obtained and was used to compute a standardized score
    (Zscore) of information content for that cell. While the
    distribution is not composed of independent samples, it was
    nominally normally distributed, and a Z value of 2.29 was chosen
    as a cut-off for significance (the equivalent of a one-tailed
    t-test with P = 0.01 under a normal distribution).

    Reference(s)
    ------------
    Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L.,
        and Skaggs, W. E. (1994). "Spatial information content and
        reliability of hippocampal CA1 neurons: effects of visual
        input", Hippocampus, 4(4), 410-421.

    Parameters
    ----------

    Returns
    -------
    si : array of shape (n_units,)
        spatial information (in bits) per spike
    """

    return utils.spatial_information(ratemap=self.ratemap, Pi=self.occupancy)

spatial_selectivity()

Compute the spatial selectivity...

Source code in nelpy/auxiliary/_tuningcurve.py
302
303
304
def spatial_selectivity(self):
    """Compute the spatial selectivity..."""
    return utils.spatial_selectivity(ratemap=self.ratemap, Pi=self.occupancy)

spatial_sparsity()

Compute the spatial information and firing sparsity...

The specificity index examines the amount of information (in bits) that a single spike conveys about the animal's location (i.e., how well cell firing predicts the animal's location).The spatial information content of cell discharge was calculated using the formula: information content = \Sum P_i(R_i/R)log_2(R_i/R) where i is the bin number, P_i, is the probability for occupancy of bin i, R_i, is the mean firing rate for bin i, and R is the overall mean firing rate.

In order to account for the effects of low firing rates (with fewer spikes there is a tendency toward higher information content) or random bursts of firing, the spike firing time-series was randomly offset in time from the rat location time-series, and the information content was calculated. A distribution of the information content based on 100 such random shifts was obtained and was used to compute a standardized score (Zscore) of information content for that cell. While the distribution is not composed of independent samples, it was nominally normally distributed, and a Z value of 2.29 was chosen as a cut-off for significance (the equivalent of a one-tailed t-test with P = 0.01 under a normal distribution).

Reference(s)

Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L., and Skaggs, W. E. (1994). "Spatial information content and reliability of hippocampal CA1 neurons: effects of visual input", Hippocampus, 4(4), 410-421.

Parameters:

Name Type Description Default
Returns
required
si array of shape (n_units,)

spatial information (in bits) per unit

required
sparsity

sparsity (in percent) for each unit

required
Source code in nelpy/auxiliary/_tuningcurve.py
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
def spatial_sparsity(self):
    """Compute the spatial information and firing sparsity...

    The specificity index examines the amount of information
    (in bits) that a single spike conveys about the animal's
    location (i.e., how well cell firing predicts the animal's
    location).The spatial information content of cell discharge was
    calculated using the formula:
        information content = \Sum P_i(R_i/R)log_2(R_i/R)
    where i is the bin number, P_i, is the probability for occupancy
    of bin i, R_i, is the mean firing rate for bin i, and R is the
    overall mean firing rate.

    In order to account for the effects of low firing rates (with
    fewer spikes there is a tendency toward higher information
    content) or random bursts of firing, the spike firing
    time-series was randomly offset in time from the rat location
    time-series, and the information content was calculated. A
    distribution of the information content based on 100 such random
    shifts was obtained and was used to compute a standardized score
    (Zscore) of information content for that cell. While the
    distribution is not composed of independent samples, it was
    nominally normally distributed, and a Z value of 2.29 was chosen
    as a cut-off for significance (the equivalent of a one-tailed
    t-test with P = 0.01 under a normal distribution).

    Reference(s)
    ------------
    Markus, E. J., Barnes, C. A., McNaughton, B. L., Gladden, V. L.,
        and Skaggs, W. E. (1994). "Spatial information content and
        reliability of hippocampal CA1 neurons: effects of visual
        input", Hippocampus, 4(4), 410-421.

    Parameters
    ----------

    Returns
    -------
    si : array of shape (n_units,)
        spatial information (in bits) per unit
    sparsity: array of shape (n_units,)
        sparsity (in percent) for each unit
    """
    return utils.spatial_sparsity(ratemap=self.ratemap, Pi=self.occupancy)

std(*, axis=None)

Returns the std of firing rate (in Hz).

Parameters:

Name Type Description Default
axis int

When axis is None, the global std firing rate is returned. When axis is 0, the std firing rates across units, as a function of the external correlate (e.g. position) are returned. When axis is 1, the std firing rate for each unit is returned.

None

Returns:

Name Type Description
std
Source code in nelpy/auxiliary/_tuningcurve.py
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
def std(self, *, axis=None):
    """Returns the std of firing rate (in Hz).
    Parameters
    ----------
    axis : int, optional
        When axis is None, the global std firing rate is returned.
        When axis is 0, the std firing rates across units, as a
        function of the external correlate (e.g. position) are
        returned.
        When axis is 1, the std firing rate for each unit is
        returned.
    Returns
    -------
    std :
    """

    if (axis is None) | (axis == 0):
        stds = np.std(self.ratemap, axis=axis)
    elif axis == 1:
        stds = [
            self.ratemap[unit_i, :, :].std()
            for unit_i in range(self.ratemap.shape[0])
        ]

    return stds

TuningCurveND

Tuning curves (N-dimensional) of multiple units.

Parameters:

Name Type Description Default
bst BinnedSpikeTrainArray

Binned spike train array for tuning curve estimation.

None
extern array - like

External correlates (e.g., position).

None
ratemap ndarray

Precomputed rate map.

None
sigma float or array - like

Standard deviation for Gaussian smoothing. If float, applied to all dimensions. If array-like, must have length equal to n_dimensions.

None
truncate float

Truncation parameter for smoothing.

None
n_bins array - like

Number of bins for each dimension.

None
transform_func callable

Function to transform external correlates.

None
minbgrate float

Minimum background firing rate.

None
ext_min array - like

Extent of the external correlates for each dimension.

None
ext_max array - like

Extent of the external correlates for each dimension.

None
extlabels list

Labels for external correlates.

None
min_duration float

Minimum duration for occupancy.

None
unit_ids list

Unit IDs.

None
unit_labels list

Unit labels.

None
unit_tags list

Unit tags.

None
label str

Label for the tuning curve.

None
empty bool

If True, create an empty TuningCurveND.

False

Attributes:

Name Type Description
ratemap ndarray

The N-D rate map with shape (n_units, *n_bins).

occupancy ndarray

Occupancy map.

unit_ids list

Unit IDs.

unit_labels list

Unit labels.

unit_tags list

Unit tags.

label str

Label for the tuning curve.

mask ndarray

Mask for valid regions.

n_dimensions int

Number of dimensions.

Examples:

>>> import numpy as np
>>> import nelpy as nel
>>> n_units = 5  # Number of units
>>> spike_times = np.sort(np.random.rand(n_units, 1000))
>>> # Create SpikeTrainArray and bin it
>>> sta = nel.SpikeTrainArray(
...     spike_times,
...     fs=1000,
... )
>>> # Bin the spike train array
>>> bst = sta.bin(ds=0.1)  # 100ms bins
>>> # Create an external AnalogSignalArray
>>> # For example, a random signal with 4 channels and 1000 samples at 10 Hz
>>> extern = nel.AnalogSignalArray(data=np.random.rand(4, 1000), fs=10.0)
>>> # Create a 4D tuning curve
>>> tuning_curve = nel.TuningCurveND(bst=bst, extern=extern, n_bins=[2, 5, 4, 3])
>>> tuning_curve.ratemap.shape
(5, 2, 5, 4, 3)  # 5 units, with bins in each of the 4 dimensions
Source code in nelpy/auxiliary/_tuningcurve.py
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
2688
2689
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
2733
2734
2735
2736
2737
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
2851
2852
2853
2854
2855
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
class TuningCurveND:
    """
    Tuning curves (N-dimensional) of multiple units.

    Parameters
    ----------
    bst : BinnedSpikeTrainArray, optional
        Binned spike train array for tuning curve estimation.
    extern : array-like, optional
        External correlates (e.g., position).
    ratemap : np.ndarray, optional
        Precomputed rate map.
    sigma : float or array-like, optional
        Standard deviation for Gaussian smoothing. If float, applied to all
        dimensions. If array-like, must have length equal to n_dimensions.
    truncate : float, optional
        Truncation parameter for smoothing.
    n_bins : array-like, optional
        Number of bins for each dimension.
    transform_func : callable, optional
        Function to transform external correlates.
    minbgrate : float, optional
        Minimum background firing rate.
    ext_min, ext_max : array-like, optional
        Extent of the external correlates for each dimension.
    extlabels : list, optional
        Labels for external correlates.
    min_duration : float, optional
        Minimum duration for occupancy.
    unit_ids : list, optional
        Unit IDs.
    unit_labels : list, optional
        Unit labels.
    unit_tags : list, optional
        Unit tags.
    label : str, optional
        Label for the tuning curve.
    empty : bool, optional
        If True, create an empty TuningCurveND.

    Attributes
    ----------
    ratemap : np.ndarray
        The N-D rate map with shape (n_units, *n_bins).
    occupancy : np.ndarray
        Occupancy map.
    unit_ids : list
        Unit IDs.
    unit_labels : list
        Unit labels.
    unit_tags : list
        Unit tags.
    label : str
        Label for the tuning curve.
    mask : np.ndarray
        Mask for valid regions.
    n_dimensions : int
        Number of dimensions.

    Examples
    --------
    >>> import numpy as np
    >>> import nelpy as nel
    >>> n_units = 5  # Number of units
    >>> spike_times = np.sort(np.random.rand(n_units, 1000))
    >>> # Create SpikeTrainArray and bin it
    >>> sta = nel.SpikeTrainArray(
    ...     spike_times,
    ...     fs=1000,
    ... )
    >>> # Bin the spike train array
    >>> bst = sta.bin(ds=0.1)  # 100ms bins
    >>> # Create an external AnalogSignalArray
    >>> # For example, a random signal with 4 channels and 1000 samples at 10 Hz
    >>> extern = nel.AnalogSignalArray(data=np.random.rand(4, 1000), fs=10.0)
    >>> # Create a 4D tuning curve
    >>> tuning_curve = nel.TuningCurveND(bst=bst, extern=extern, n_bins=[2, 5, 4, 3])
    >>> tuning_curve.ratemap.shape
    (5, 2, 5, 4, 3)  # 5 units, with bins in each of the 4 dimensions
    """

    __attributes__ = [
        "_ratemap",
        "_occupancy",
        "_unit_ids",
        "_unit_labels",
        "_unit_tags",
        "_label",
        "_mask",
        "_n_dimensions",
        "_bins_list",
        "_extlabels",
    ]

    @keyword_deprecation(replace_x_with_y={"bw": "truncate"})
    def __init__(
        self,
        *,
        bst=None,
        extern=None,
        ratemap=None,
        sigma=None,
        truncate=None,
        n_bins=None,
        transform_func=None,
        minbgrate=None,
        ext_min=None,
        ext_max=None,
        extlabels=None,
        min_duration=None,
        unit_ids=None,
        unit_labels=None,
        unit_tags=None,
        label=None,
        empty=False,
    ):
        """
        Initialize TuningCurveND object.

        NOTE: tuning curves in ND have shapes (n_units, *n_bins) so that
        the first dimension is always n_units, followed by the spatial dimensions.

        If sigma is nonzero, then smoothing is applied.

        We always require bst and extern, and then some combination of
            (1) n_bins, ext_min, ext_max, transform_func*
            (2) bin edges, transform_func*

            transform_func operates on extern and returns a 2D array of shape
            (n_dimensions, n_timepoints). If no transform is specified, the
            identity operator is assumed.
        """
        # TODO: input validation
        if not empty:
            if ratemap is None:
                assert bst is not None, (
                    "bst must be specified or ratemap must be specified!"
                )
                assert extern is not None, (
                    "extern must be specified or ratemap must be specified!"
                )
            else:
                assert bst is None, "ratemap and bst cannot both be specified!"
                assert extern is None, "ratemap and extern cannot both be specified!"

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

        if ratemap is not None:
            for attr in self.__attributes__:
                exec("self." + attr + " = None")
            self._init_from_ratemap(
                ratemap=ratemap,
                ext_min=ext_min,
                ext_max=ext_max,
                extlabels=extlabels,
                unit_ids=unit_ids,
                unit_labels=unit_labels,
                unit_tags=unit_tags,
                label=label,
            )
            return

        self._mask = None  # TODO: change this when we can learn a mask in __init__!
        self._bst = bst
        self._extern = extern

        if minbgrate is None:
            minbgrate = 0.01  # Hz minimum background firing rate

        # Handle n_bins parameter
        if n_bins is not None:
            n_bins = np.asarray(n_bins, dtype=int)
            if n_bins.ndim == 0:
                raise ValueError("n_bins must be array-like for ND tuning curves")
            self._n_dimensions = len(n_bins)

            # Set default ext_min and ext_max if not provided
            if ext_min is None:
                ext_min = np.zeros(self._n_dimensions)
            if ext_max is None:
                ext_max = np.ones(self._n_dimensions)

            ext_min = np.asarray(ext_min)
            ext_max = np.asarray(ext_max)

            if len(ext_min) != self._n_dimensions or len(ext_max) != self._n_dimensions:
                raise ValueError(
                    "ext_min and ext_max must have length equal to n_dimensions"
                )

            # Create bin edges for each dimension
            self._bins_list = []
            for i in range(self._n_dimensions):
                bins = np.linspace(ext_min[i], ext_max[i], n_bins[i] + 1)
                self._bins_list.append(bins)
        else:
            raise NotImplementedError("Must specify n_bins for TuningCurveND")

        if min_duration is None:
            min_duration = 0

        self._min_duration = min_duration
        self._unit_ids = bst.unit_ids
        self._unit_labels = bst.unit_labels
        self._unit_tags = bst.unit_tags  # no input validation yet
        self.label = label

        # Set extlabels
        if extlabels is None:
            self._extlabels = [f"dim_{i}" for i in range(self._n_dimensions)]
        else:
            if len(extlabels) != self._n_dimensions:
                raise ValueError("extlabels must have length equal to n_dimensions")
            self._extlabels = extlabels

        if transform_func is None:
            self.trans_func = self._trans_func
        else:
            self.trans_func = transform_func

        # compute occupancy
        self._occupancy = self._compute_occupancy()
        # compute ratemap (in Hz)
        self._ratemap = self._compute_ratemap()
        # normalize firing rate by occupancy
        self._ratemap = self._normalize_firing_rate_by_occupancy()
        # enforce minimum background firing rate
        self._ratemap[self._ratemap < minbgrate] = (
            minbgrate  # background firing rate of 0.01 Hz
        )

        if sigma is not None:
            if np.any(np.asarray(sigma) > 0):
                self.smooth(sigma=sigma, truncate=truncate, inplace=True)

        # optionally detach _bst and _extern to save space when pickling, for example
        self._detach()

    def spatial_information(self):
        """Compute the spatial information and firing sparsity..."""
        return utils.spatial_information(ratemap=self.ratemap, Pi=self.occupancy)

    def information_rate(self):
        """Compute the information rate..."""
        return utils.information_rate(ratemap=self.ratemap, Pi=self.occupancy)

    def spatial_selectivity(self):
        """Compute the spatial selectivity..."""
        return utils.spatial_selectivity(ratemap=self.ratemap, Pi=self.occupancy)

    def spatial_sparsity(self):
        """Compute the spatial information and firing sparsity..."""
        return utils.spatial_sparsity(ratemap=self.ratemap, Pi=self.occupancy)

    def __add__(self, other):
        out = copy.copy(self)

        if isinstance(other, numbers.Number):
            out._ratemap = out.ratemap + other
        elif isinstance(other, TuningCurveND):
            # TODO: this should merge two TuningCurveND objects
            raise NotImplementedError
        else:
            raise TypeError(
                "unsupported operand type(s) for +: 'TuningCurveND' and '{}'".format(
                    str(type(other))
                )
            )
        return out

    def __sub__(self, other):
        out = copy.copy(self)
        out._ratemap = out.ratemap - other
        return out

    def __mul__(self, other):
        """overloaded * operator."""
        out = copy.copy(self)
        out._ratemap = out.ratemap * other
        return out

    def __rmul__(self, other):
        return self * other

    def __truediv__(self, other):
        """overloaded / operator."""
        out = copy.copy(self)
        out._ratemap = out.ratemap / other
        return out

    def _init_from_ratemap(
        self,
        ratemap,
        occupancy=None,
        ext_min=None,
        ext_max=None,
        extlabels=None,
        unit_ids=None,
        unit_labels=None,
        unit_tags=None,
        label=None,
    ):
        """Initialize a TuningCurveND object from a ratemap.

        Parameters
        ----------
        ratemap : array
            Array of shape (n_units, *n_bins)
        """
        self._n_dimensions = ratemap.ndim - 1  # subtract 1 for units dimension
        n_units = ratemap.shape[0]
        bin_shape = ratemap.shape[1:]

        if occupancy is None:
            # assume uniform occupancy
            self._occupancy = np.ones(bin_shape)

        if ext_min is None:
            ext_min = np.zeros(self._n_dimensions)
        if ext_max is None:
            ext_max = np.ones(self._n_dimensions)

        ext_min = np.asarray(ext_min)
        ext_max = np.asarray(ext_max)

        self._bins_list = []
        for i in range(self._n_dimensions):
            bins = np.linspace(ext_min[i], ext_max[i], bin_shape[i] + 1)
            self._bins_list.append(bins)

        self._ratemap = ratemap

        # inherit unit IDs if available, otherwise initialize to default
        if unit_ids is None:
            unit_ids = list(range(1, n_units + 1))

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

        # if unit_labels is empty, default to unit_ids
        if unit_labels is None:
            unit_labels = unit_ids

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

        self._unit_ids = unit_ids
        self._unit_labels = unit_labels
        self._unit_tags = unit_tags  # no input validation yet

        # Set extlabels
        if extlabels is None:
            self._extlabels = [f"dim_{i}" for i in range(self._n_dimensions)]
        else:
            if len(extlabels) != self._n_dimensions:
                raise ValueError("extlabels must have length equal to n_dimensions")
            self._extlabels = extlabels

        if label is not None:
            self.label = label

        return self

    def max(self, *, axis=None):
        """Returns the max of firing rate (in Hz)."""
        if axis is None or axis == 0:
            maxes = np.max(self.ratemap, axis=axis)
        elif axis == 1:
            # Flatten all spatial dimensions for per-unit calculation
            maxes = [
                self.ratemap[unit_i].max() for unit_i in range(self.ratemap.shape[0])
            ]
        else:
            maxes = np.max(self.ratemap, axis=axis)

        return maxes

    def min(self, *, axis=None):
        """Returns the min of firing rate (in Hz)."""
        if axis is None or axis == 0:
            mins = np.min(self.ratemap, axis=axis)
        elif axis == 1:
            # Flatten all spatial dimensions for per-unit calculation
            mins = [
                self.ratemap[unit_i].min() for unit_i in range(self.ratemap.shape[0])
            ]
        else:
            mins = np.min(self.ratemap, axis=axis)

        return mins

    def mean(self, *, axis=None):
        """Returns the mean of firing rate (in Hz)."""
        if axis is None or axis == 0:
            means = np.mean(self.ratemap, axis=axis)
        elif axis == 1:
            # Flatten all spatial dimensions for per-unit calculation
            means = [
                self.ratemap[unit_i].mean() for unit_i in range(self.ratemap.shape[0])
            ]
        else:
            means = np.mean(self.ratemap, axis=axis)

        return means

    def std(self, *, axis=None):
        """Returns the std of firing rate (in Hz)."""
        if axis is None or axis == 0:
            stds = np.std(self.ratemap, axis=axis)
        elif axis == 1:
            # Flatten all spatial dimensions for per-unit calculation
            stds = [
                self.ratemap[unit_i].std() for unit_i in range(self.ratemap.shape[0])
            ]
        else:
            stds = np.std(self.ratemap, axis=axis)

        return stds

    def _detach(self):
        """Detach bst and extern from tuning curve."""
        self._bst = None
        self._extern = None

    @property
    def mask(self):
        """Mask for tuning curve."""
        return self._mask

    @property
    def n_bins(self):
        """Total number of bins (product of bins in all dimensions)."""
        return np.prod([len(bins) - 1 for bins in self._bins_list])

    @property
    def n_bins_per_dim(self):
        """Number of bins for each dimension."""
        return [len(bins) - 1 for bins in self._bins_list]

    @property
    def bins(self):
        """List of bin edges for each dimension."""
        return self._bins_list

    @property
    def bin_centers(self):
        """List of bin centers for each dimension."""
        centers = []
        for bins in self._bins_list:
            center = (bins + (bins[1] - bins[0]) / 2)[:-1]
            centers.append(center)
        return centers

    @property
    def n_dimensions(self):
        """Number of dimensions."""
        return self._n_dimensions

    @property
    def extlabels(self):
        """Labels for external correlates."""
        return self._extlabels

    # Backwards compatibility properties for 1D and 2D cases
    @property
    def xbins(self):
        """X-dimension bins (for backwards compatibility when n_dimensions >= 1)."""
        if self._n_dimensions >= 1:
            return self._bins_list[0]
        else:
            raise AttributeError("xbins not available for 0-dimensional tuning curves")

    @property
    def ybins(self):
        """Y-dimension bins (for backwards compatibility when n_dimensions >= 2)."""
        if self._n_dimensions >= 2:
            return self._bins_list[1]
        else:
            raise AttributeError(
                "ybins not available for tuning curves with < 2 dimensions"
            )

    @property
    def n_xbins(self):
        """Number of X-dimension bins (for backwards compatibility)."""
        if self._n_dimensions >= 1:
            return len(self._bins_list[0]) - 1
        else:
            raise AttributeError(
                "n_xbins not available for 0-dimensional tuning curves"
            )

    @property
    def n_ybins(self):
        """Number of Y-dimension bins (for backwards compatibility)."""
        if self._n_dimensions >= 2:
            return len(self._bins_list[1]) - 1
        else:
            raise AttributeError(
                "n_ybins not available for tuning curves with < 2 dimensions"
            )

    @property
    def xbin_centers(self):
        """X-dimension bin centers (for backwards compatibility)."""
        if self._n_dimensions >= 1:
            bins = self._bins_list[0]
            return (bins + (bins[1] - bins[0]) / 2)[:-1]
        else:
            raise AttributeError(
                "xbin_centers not available for 0-dimensional tuning curves"
            )

    @property
    def ybin_centers(self):
        """Y-dimension bin centers (for backwards compatibility)."""
        if self._n_dimensions >= 2:
            bins = self._bins_list[1]
            return (bins + (bins[1] - bins[0]) / 2)[:-1]
        else:
            raise AttributeError(
                "ybin_centers not available for tuning curves with < 2 dimensions"
            )

    @property
    def is2d(self):
        """Check if this is a 2D tuning curve."""
        return self._n_dimensions == 2

    def _trans_func(self, extern, at):
        """Default transform function to map extern into numerical bins.

        Returns
        -------
        coords : np.ndarray
            Array of shape (n_dimensions, n_timepoints)
        """
        _, ext = extern.asarray(at=at)

        # If extern has shape (n_signals, n_timepoints), use first n_dimensions signals
        if ext.ndim == 2 and ext.shape[0] >= self._n_dimensions:
            coords = ext[: self._n_dimensions, :]
        # If extern is 1D and we need 1 dimension, reshape appropriately
        elif ext.ndim == 1 and self._n_dimensions == 1:
            coords = ext.reshape(1, -1)
        else:
            raise ValueError(
                f"extern shape {ext.shape} incompatible with {self._n_dimensions} dimensions"
            )

        return coords

    def __getitem__(self, *idx):
        """TuningCurveND index access. Accepts integers, slices, and lists"""
        idx = [ii for ii in idx]
        if len(idx) == 1 and not isinstance(idx[0], int):
            idx = idx[0]
        if isinstance(idx, tuple):
            idx = [ii for ii in idx]

        if self.isempty:
            return self
        try:
            out = copy.copy(self)
            out._ratemap = self.ratemap[idx]
            out._unit_ids = (np.asanyarray(out._unit_ids)[idx]).tolist()
            out._unit_labels = (np.asanyarray(out._unit_labels)[idx]).tolist()
            return out
        except Exception:
            raise TypeError("unsupported subscripting type {}".format(type(idx)))

    def _compute_occupancy(self):
        """Compute occupancy using np.histogramdd."""
        # Make sure that self._bst_centers fall within not only the support
        # of extern, but also within the extreme sample times
        if self._bst._bin_centers[0] < self._extern.time[0]:
            self._extern = copy.copy(self._extern)
            self._extern.time[0] = self._bst._bin_centers[0]
            self._extern._interp = None

        if self._bst._bin_centers[-1] > self._extern.time[-1]:
            self._extern = copy.copy(self._extern)
            self._extern.time[-1] = self._bst._bin_centers[-1]
            self._extern._interp = None

        coords = self.trans_func(self._extern, at=self._bst.bin_centers)

        # coords should be shape (n_dimensions, n_timepoints)
        # transpose to (n_timepoints, n_dimensions) for histogramdd
        coords_transposed = coords.T

        # Create ranges for histogramdd
        ranges = []
        for bins in self._bins_list:
            ranges.append([bins[0], bins[-1]])

        occupancy, _ = np.histogramdd(
            coords_transposed, bins=self._bins_list, range=ranges
        )

        return occupancy

    def _compute_ratemap(self, min_duration=None):
        """Compute ratemap using N-dimensional binning."""
        if min_duration is None:
            min_duration = self._min_duration

        coords = self.trans_func(self._extern, at=self._bst.bin_centers)

        # Get bin indices for each dimension
        bin_indices = []
        for i, bins in enumerate(self._bins_list):
            indices = np.digitize(coords[i, :], bins, right=True)
            bin_indices.append(indices)

        # Check bounds for all dimensions
        for i, (indices, bins) in enumerate(zip(bin_indices, self._bins_list)):
            n_bins_dim = len(bins) - 1
            if indices.max() > n_bins_dim:
                raise ValueError(f"ext values greater than 'ext_max' in dimension {i}")
            if indices.min() == 0:
                raise ValueError(f"ext values less than 'ext_min' in dimension {i}")

        # Initialize ratemap
        ratemap_shape = (self.n_units,) + tuple(self.n_bins_per_dim)
        ratemap = np.zeros(ratemap_shape)

        # Accumulate spikes in appropriate bins
        for tt in range(len(self._bst.bin_centers)):
            # Get bin coordinates for this time point
            bin_coords = tuple(
                idx[tt] - 1 for idx in bin_indices
            )  # subtract 1 for 0-indexing

            # Check if all coordinates are valid (within bounds)
            if all(
                0 <= coord < dim_size
                for coord, dim_size in zip(bin_coords, self.n_bins_per_dim)
            ):
                # Use advanced indexing to add spike counts for all units
                for unit_idx in range(self.n_units):
                    ratemap[(unit_idx,) + bin_coords] += self._bst.data[unit_idx, tt]

        # Apply minimum observation duration
        for uu in range(self.n_units):
            ratemap[uu][self.occupancy * self._bst.ds < min_duration] = 0

        return ratemap / self._bst.ds

    def _normalize_firing_rate_by_occupancy(self):
        """Normalize spike counts by occupancy."""
        # Tile occupancy to match ratemap shape
        occupancy_tiled = np.tile(
            self.occupancy, (self.n_units,) + (1,) * self._n_dimensions
        )
        occupancy_tiled[occupancy_tiled == 0] = 1
        ratemap = self.ratemap / occupancy_tiled
        return ratemap

    @property
    def occupancy(self):
        return self._occupancy

    @property
    def n_units(self):
        """(int) The number of units."""
        try:
            return len(self._unit_ids)
        except TypeError:  # when unit_ids is an integer
            return 1
        except AttributeError:
            return 0

    @property
    def shape(self):
        """(tuple) The shape of the TuningCurveND ratemap."""
        if self.isempty:
            return (self.n_units,) + (0,) * self._n_dimensions
        return self.ratemap.shape

    def __repr__(self):
        address_str = " at " + str(hex(id(self)))
        if self.isempty:
            return f"<empty TuningCurveND{address_str}>"
        shapestr = " with shape " + str(self.shape)
        return f"<TuningCurveND({self._n_dimensions}D){address_str}>{shapestr}"

    @property
    def isempty(self):
        """(bool) True if TuningCurveND is empty"""
        try:
            return len(self.ratemap) == 0
        except TypeError:  # TypeError should happen if ratemap = []
            return True

    @property
    def ratemap(self):
        return self._ratemap

    def __len__(self):
        return self.n_units

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

    def __next__(self):
        """TuningCurveND iterator advancer."""
        index = self._index
        if index > self.n_units - 1:
            raise StopIteration
        out = copy.copy(self)
        out._ratemap = self.ratemap[index][np.newaxis, ...]  # Keep unit dimension
        out._unit_ids = [self.unit_ids[index]]
        out._unit_labels = [self.unit_labels[index]]
        self._index += 1
        return out

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

        Parameters
        ----------
        sigma : float or array-like, optional
            Standard deviation for Gaussian smoothing. If float, applied to all
            dimensions. If array-like, must have length equal to n_dimensions.
        """
        if sigma is None:
            sigma = 0.1  # in units of extern
        if truncate is None:
            truncate = 4
        if mode is None:
            mode = "reflect"
        if cval is None:
            cval = 0.0

        # Handle sigma parameter
        sigma_array = np.asarray(sigma)
        if sigma_array.ndim == 0:
            # Single sigma value - apply to all dimensions
            sigma_values = np.full(self._n_dimensions, float(sigma_array))
        else:
            # Array of sigma values
            if len(sigma_array) != self._n_dimensions:
                raise ValueError(
                    f"sigma array length {len(sigma_array)} must equal n_dimensions {self._n_dimensions}"
                )
            sigma_values = sigma_array

        # Convert sigma from extern units to pixel units for each dimension
        sigma_pixels = []
        for i, (bins, sigma_val) in enumerate(zip(self._bins_list, sigma_values)):
            ds = (bins[-1] - bins[0]) / (len(bins) - 1)
            sigma_pixels.append(sigma_val / ds)

        # Create full sigma tuple: (0, sigma_dim0, sigma_dim1, ...)
        full_sigma = (0,) + tuple(sigma_pixels)

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

        if self.mask is None:
            # Simple case without mask
            out._ratemap = scipy.ndimage.gaussian_filter(
                self.ratemap,
                sigma=full_sigma,
                truncate=truncate,
                mode=mode,
                cval=cval,
            )
        else:
            # Complex case with mask - handle NaNs properly
            masked_ratemap = self.ratemap.copy() * self.mask
            V = masked_ratemap.copy()
            V[masked_ratemap != masked_ratemap] = 0
            W = 0 * masked_ratemap.copy() + 1
            W[masked_ratemap != masked_ratemap] = 0

            VV = scipy.ndimage.filters.gaussian_filter(
                V,
                sigma=full_sigma,
                truncate=truncate,
                mode=mode,
                cval=cval,
            )
            WW = scipy.ndimage.filters.gaussian_filter(
                W,
                sigma=full_sigma,
                truncate=truncate,
                mode=mode,
                cval=cval,
            )
            Z = VV / WW
            out._ratemap = Z * self.mask

        return out

    @property
    def unit_ids(self):
        """Unit IDs contained in the SpikeTrain."""
        return list(self._unit_ids)

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

    @property
    def unit_labels(self):
        """Labels corresponding to units contained in the SpikeTrain."""
        if self._unit_labels is None:
            warnings.warn("unit labels have not yet been specified")
        return self._unit_labels

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

    @property
    def unit_tags(self):
        """Tags corresponding to units contained in the SpikeTrain"""
        if self._unit_tags is None:
            warnings.warn("unit tags have not yet been specified")
        return self._unit_tags

    @property
    def label(self):
        """Label pertaining to the source of the spike train."""
        if self._label is None:
            warnings.warn("label has not yet been specified")
        return self._label

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

bin_centers property

List of bin centers for each dimension.

bins property

List of bin edges for each dimension.

extlabels property

Labels for external correlates.

is2d property

Check if this is a 2D tuning curve.

isempty property

(bool) True if TuningCurveND is empty

label property writable

Label pertaining to the source of the spike train.

mask property

Mask for tuning curve.

n_bins property

Total number of bins (product of bins in all dimensions).

n_bins_per_dim property

Number of bins for each dimension.

n_dimensions property

Number of dimensions.

n_units property

(int) The number of units.

n_xbins property

Number of X-dimension bins (for backwards compatibility).

n_ybins property

Number of Y-dimension bins (for backwards compatibility).

shape property

(tuple) The shape of the TuningCurveND ratemap.

unit_ids property writable

Unit IDs contained in the SpikeTrain.

unit_labels property writable

Labels corresponding to units contained in the SpikeTrain.

unit_tags property

Tags corresponding to units contained in the SpikeTrain

xbin_centers property

X-dimension bin centers (for backwards compatibility).

xbins property

X-dimension bins (for backwards compatibility when n_dimensions >= 1).

ybin_centers property

Y-dimension bin centers (for backwards compatibility).

ybins property

Y-dimension bins (for backwards compatibility when n_dimensions >= 2).

information_rate()

Compute the information rate...

Source code in nelpy/auxiliary/_tuningcurve.py
2374
2375
2376
def information_rate(self):
    """Compute the information rate..."""
    return utils.information_rate(ratemap=self.ratemap, Pi=self.occupancy)

max(*, axis=None)

Returns the max of firing rate (in Hz).

Source code in nelpy/auxiliary/_tuningcurve.py
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
def max(self, *, axis=None):
    """Returns the max of firing rate (in Hz)."""
    if axis is None or axis == 0:
        maxes = np.max(self.ratemap, axis=axis)
    elif axis == 1:
        # Flatten all spatial dimensions for per-unit calculation
        maxes = [
            self.ratemap[unit_i].max() for unit_i in range(self.ratemap.shape[0])
        ]
    else:
        maxes = np.max(self.ratemap, axis=axis)

    return maxes

mean(*, axis=None)

Returns the mean of firing rate (in Hz).

Source code in nelpy/auxiliary/_tuningcurve.py
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
def mean(self, *, axis=None):
    """Returns the mean of firing rate (in Hz)."""
    if axis is None or axis == 0:
        means = np.mean(self.ratemap, axis=axis)
    elif axis == 1:
        # Flatten all spatial dimensions for per-unit calculation
        means = [
            self.ratemap[unit_i].mean() for unit_i in range(self.ratemap.shape[0])
        ]
    else:
        means = np.mean(self.ratemap, axis=axis)

    return means

min(*, axis=None)

Returns the min of firing rate (in Hz).

Source code in nelpy/auxiliary/_tuningcurve.py
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
def min(self, *, axis=None):
    """Returns the min of firing rate (in Hz)."""
    if axis is None or axis == 0:
        mins = np.min(self.ratemap, axis=axis)
    elif axis == 1:
        # Flatten all spatial dimensions for per-unit calculation
        mins = [
            self.ratemap[unit_i].min() for unit_i in range(self.ratemap.shape[0])
        ]
    else:
        mins = np.min(self.ratemap, axis=axis)

    return mins

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

Smooths the tuning curve with a Gaussian kernel.

Parameters:

Name Type Description Default
sigma float or array - like

Standard deviation for Gaussian smoothing. If float, applied to all dimensions. If array-like, must have length equal to n_dimensions.

None
Source code in nelpy/auxiliary/_tuningcurve.py
2850
2851
2852
2853
2854
2855
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
@keyword_deprecation(replace_x_with_y={"bw": "truncate"})
def smooth(self, *, sigma=None, truncate=None, inplace=False, mode=None, cval=None):
    """Smooths the tuning curve with a Gaussian kernel.

    Parameters
    ----------
    sigma : float or array-like, optional
        Standard deviation for Gaussian smoothing. If float, applied to all
        dimensions. If array-like, must have length equal to n_dimensions.
    """
    if sigma is None:
        sigma = 0.1  # in units of extern
    if truncate is None:
        truncate = 4
    if mode is None:
        mode = "reflect"
    if cval is None:
        cval = 0.0

    # Handle sigma parameter
    sigma_array = np.asarray(sigma)
    if sigma_array.ndim == 0:
        # Single sigma value - apply to all dimensions
        sigma_values = np.full(self._n_dimensions, float(sigma_array))
    else:
        # Array of sigma values
        if len(sigma_array) != self._n_dimensions:
            raise ValueError(
                f"sigma array length {len(sigma_array)} must equal n_dimensions {self._n_dimensions}"
            )
        sigma_values = sigma_array

    # Convert sigma from extern units to pixel units for each dimension
    sigma_pixels = []
    for i, (bins, sigma_val) in enumerate(zip(self._bins_list, sigma_values)):
        ds = (bins[-1] - bins[0]) / (len(bins) - 1)
        sigma_pixels.append(sigma_val / ds)

    # Create full sigma tuple: (0, sigma_dim0, sigma_dim1, ...)
    full_sigma = (0,) + tuple(sigma_pixels)

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

    if self.mask is None:
        # Simple case without mask
        out._ratemap = scipy.ndimage.gaussian_filter(
            self.ratemap,
            sigma=full_sigma,
            truncate=truncate,
            mode=mode,
            cval=cval,
        )
    else:
        # Complex case with mask - handle NaNs properly
        masked_ratemap = self.ratemap.copy() * self.mask
        V = masked_ratemap.copy()
        V[masked_ratemap != masked_ratemap] = 0
        W = 0 * masked_ratemap.copy() + 1
        W[masked_ratemap != masked_ratemap] = 0

        VV = scipy.ndimage.filters.gaussian_filter(
            V,
            sigma=full_sigma,
            truncate=truncate,
            mode=mode,
            cval=cval,
        )
        WW = scipy.ndimage.filters.gaussian_filter(
            W,
            sigma=full_sigma,
            truncate=truncate,
            mode=mode,
            cval=cval,
        )
        Z = VV / WW
        out._ratemap = Z * self.mask

    return out

spatial_information()

Compute the spatial information and firing sparsity...

Source code in nelpy/auxiliary/_tuningcurve.py
2370
2371
2372
def spatial_information(self):
    """Compute the spatial information and firing sparsity..."""
    return utils.spatial_information(ratemap=self.ratemap, Pi=self.occupancy)

spatial_selectivity()

Compute the spatial selectivity...

Source code in nelpy/auxiliary/_tuningcurve.py
2378
2379
2380
def spatial_selectivity(self):
    """Compute the spatial selectivity..."""
    return utils.spatial_selectivity(ratemap=self.ratemap, Pi=self.occupancy)

spatial_sparsity()

Compute the spatial information and firing sparsity...

Source code in nelpy/auxiliary/_tuningcurve.py
2382
2383
2384
def spatial_sparsity(self):
    """Compute the spatial information and firing sparsity..."""
    return utils.spatial_sparsity(ratemap=self.ratemap, Pi=self.occupancy)

std(*, axis=None)

Returns the std of firing rate (in Hz).

Source code in nelpy/auxiliary/_tuningcurve.py
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
def std(self, *, axis=None):
    """Returns the std of firing rate (in Hz)."""
    if axis is None or axis == 0:
        stds = np.std(self.ratemap, axis=axis)
    elif axis == 1:
        # Flatten all spatial dimensions for per-unit calculation
        stds = [
            self.ratemap[unit_i].std() for unit_i in range(self.ratemap.shape[0])
        ]
    else:
        stds = np.std(self.ratemap, axis=axis)

    return stds

load_pkl(fname, zip=True)

Read pickled data from disk, possible decompressing.

Source code in nelpy/auxiliary/_results.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def load_pkl(fname, zip=True):
    """Read pickled data from disk, possible decompressing."""
    if zip:
        try:
            with gzip.open(fname, "rb") as fid:
                res = pickle.load(fid)
        except OSError:
            # most likely, results were not saved using zip=True, so let's try
            # to load without zip:
            with open(fname, "rb") as fid:
                res = pickle.load(fid)
    else:
        with open(fname, "rb") as fid:
            res = pickle.load(fid)
    return res

save_pkl(fname, res, zip=True, overwrite=False)

Write pickled data to disk, possible compressing.

Source code in nelpy/auxiliary/_results.py
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
def save_pkl(fname, res, zip=True, overwrite=False):
    """Write pickled data to disk, possible compressing."""
    if os.path.isfile(fname):
        # file exists
        if overwrite:
            pass
        else:
            print('File "{}" already exists! Aborting...'.format(fname))
            return
    if zip:
        save_large_file_without_zip = False
        with gzip.open(fname, "wb") as fid:
            try:
                pickle.dump(res, fid)
            except OverflowError:
                print(
                    "writing to disk using protocol=4, which supports file sizes > 4 GiB, and ignoring zip=True (zip is not supported for large files yet)"
                )
                save_large_file_without_zip = True

        if save_large_file_without_zip:
            with open(fname, "wb") as fid:
                pickle.dump(res, fid, protocol=4)
    else:
        with open(fname, "wb") as fid:
            try:
                pickle.dump(res, fid)
            except OverflowError:
                print(
                    "writing to disk using protocol=4, which supports file sizes > 4 GiB"
                )
                pickle.dump(res, fid, protocol=4)