Skip to content

Estimators API Reference

BayesianDecoderTemp

Bases: BaseEstimator

Bayesian decoder wrapper class.

This class implements a Bayesian decoder for neural data, supporting various estimation modes.

Parameters:

Name Type Description Default
rate_estimator FiringRateEstimator

The firing rate estimator to use.

None
w any

Window parameter for decoding.

None
ratemap RateMap

Precomputed rate map.

None

Attributes:

Name Type Description
rate_estimator FiringRateEstimator

The firing rate estimator.

ratemap RateMap

The estimated or provided rate map.

w any

Window parameter.

Source code in nelpy/estimators.py
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
class BayesianDecoderTemp(BaseEstimator):
    """
    Bayesian decoder wrapper class.

    This class implements a Bayesian decoder for neural data, supporting various estimation modes.

    Parameters
    ----------
    rate_estimator : FiringRateEstimator, optional
        The firing rate estimator to use.
    w : any, optional
        Window parameter for decoding.
    ratemap : RateMap, optional
        Precomputed rate map.

    Attributes
    ----------
    rate_estimator : FiringRateEstimator
        The firing rate estimator.
    ratemap : RateMap
        The estimated or provided rate map.
    w : any
        Window parameter.
    """

    def __init__(self, rate_estimator=None, w=None, ratemap=None):
        self._rate_estimator = self._validate_rate_estimator(rate_estimator)
        self._ratemap = self._validate_ratemap(ratemap)
        self._w = self._validate_window(w)

    @property
    def rate_estimator(self):
        return self._rate_estimator

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

    @property
    def w(self):
        return self._w

    @staticmethod
    def _validate_rate_estimator(rate_estimator):
        if rate_estimator is None:
            rate_estimator = FiringRateEstimator()
        elif not isinstance(rate_estimator, FiringRateEstimator):
            raise TypeError(
                "'rate_estimator' must be a nelpy FiringRateEstimator() type!"
            )
        return rate_estimator

    @staticmethod
    def _validate_ratemap(ratemap):
        if ratemap is None:
            ratemap = NDRateMap()
        elif not isinstance(ratemap, NDRateMap):
            raise TypeError("'ratemap' must be a nelpy RateMap() type!")
        return ratemap

    @staticmethod
    def _validate_window(w):
        if w is None:
            w = DataWindow(sum=True, bin_width=1)
        elif not isinstance(w, DataWindow):
            raise TypeError("w must be a nelpy DataWindow() type!")
        else:
            w = copy.copy(w)
        if w._sum is False:
            logging.warning(
                "BayesianDecoder requires DataWindow (w) to have sum=True; changing to True"
            )
            w._sum = True
        if w.bin_width is None:
            w.bin_width = 1
        return w

    def _check_X_dt(self, X, *, lengths=None, dt=None):
        if isinstance(X, core.BinnedEventArray):
            if dt is not None:
                logging.warning(
                    "A {} was passed in, so 'dt' will be ignored...".format(X.type_name)
                )
            dt = X.ds
            if self._w.bin_width != dt:
                raise ValueError(
                    "BayesianDecoder was fit with a bin_width of {}, but is being used to predict data with a bin_width of {}".format(
                        self.w.bin_width, dt
                    )
                )
            X, T = self.w.transform(X, lengths=lengths, sum=True)
        else:
            if dt is not None:
                if self._w.bin_width != dt:
                    raise ValueError(
                        "BayesianDecoder was fit with a bin_width of {}, but is being used to predict data with a bin_width of {}".format(
                            self.w.bin_width, dt
                        )
                    )
            else:
                dt = self._w.bin_width

        return X, dt

    def _check_X_y(self, X, y, *, method="score", lengths=None):
        if isinstance(X, core.BinnedEventArray):
            if method == "fit":
                self._w.bin_width = X.ds
                logging.info("Updating DataWindow.bin_width from training data.")
            else:
                if self._w.bin_width != X.ds:
                    raise ValueError(
                        "BayesianDecoder was fit with a bin_width of {}, but is being used to predict data with a bin_width of {}".format(
                            self.w.bin_width, X.ds
                        )
                    )

            X, T = self.w.transform(X, lengths=lengths, sum=True)

            if isinstance(y, core.RegularlySampledAnalogSignalArray):
                y = y(T).T

        if isinstance(y, core.RegularlySampledAnalogSignalArray):
            raise TypeError(
                "y can only be a RegularlySampledAnalogSignalArray if X is a BinnedEventArray."
            )

        assert len(X) == len(y), "X and y must have the same number of samples!"

        return X, y

    def _ratemap_permute_unit_order(self, unit_ids, inplace=False):
        """Permute the unit ordering.

        If no order is specified, and an ordering exists from fit(), then the
        data in X will automatically be permuted to match that registered during
        fit().

        Parameters
        ----------
        unit_ids : array-like, shape (n_units,)
        """
        unit_ids = self._check_unit_ids(unit_ids=unit_ids)
        if len(unit_ids) != len(self.unit_ids):
            raise ValueError(
                "To re-order (permute) units, 'unit_ids' must have the same length as self._unit_ids."
            )
        self._ratemap.reorder_units_by_ids(unit_ids, inplace=inplace)

    def _check_unit_ids(self, *, X=None, unit_ids=None, fit=False):
        """Check that unit_ids are valid (if provided), and return unit_ids.

        if calling from fit(), pass in fit=True, which will skip checks against
        self.ratemap, which doesn't exist before fitting...

        """

        def a_contains_b(a, b):
            """Returns True iff 'b' is a subset of 'a'."""
            for bb in b:
                if bb not in a:
                    logging.warning("{} was not found in set".format(bb))
                    return False
            return True

        if isinstance(X, core.BinnedEventArray):
            if unit_ids is not None:
                # unit_ids were passed in, even though it's also contained in X.unit_ids
                # 1. check that unit_ids are contained in the data:
                if not a_contains_b(X.series_ids, unit_ids):
                    raise ValueError("Some unit_ids were not contained in X!")
                # 2. check that unit_ids are contained in self (decoder ratemap)
                if not fit:
                    if not a_contains_b(self.unit_ids, unit_ids):
                        raise ValueError("Some unit_ids were not contained in ratemap!")
            else:
                # infer unit_ids from X
                unit_ids = X.series_ids
                # check that unit_ids are contained in self (decoder ratemap)
                if not fit:
                    if not a_contains_b(self.unit_ids, unit_ids):
                        raise ValueError(
                            "Some unit_ids from X were not contained in ratemap!"
                        )
        else:  # a non-nelpy X was passed, possibly X=None
            if unit_ids is not None:
                # 1. check that unit_ids are contained in self (decoder ratemap)
                if not fit:
                    if not a_contains_b(self.unit_ids, unit_ids):
                        raise ValueError("Some unit_ids were not contained in ratemap!")
            else:  # no unit_ids were passed, only a non-nelpy X
                if X is not None:
                    n_samples, n_units = X.shape
                    if not fit:
                        if n_units > self.n_units:
                            raise ValueError(
                                "X contains more units than decoder! {} > {}".format(
                                    n_units, self.n_units
                                )
                            )
                        unit_ids = self.unit_ids[:n_units]
                    else:
                        unit_ids = np.arange(n_units)
                else:
                    raise NotImplementedError("unexpected branch reached...")
        return unit_ids

    def _get_transformed_ratemap(self, unit_ids):
        # first, trim ratemap to subset of units
        ratemap = self.ratemap.loc[unit_ids]
        # then, permute the ratemap
        ratemap = ratemap.reorder_units_by_ids(
            unit_ids
        )  # maybe unneccessary, since .loc already permutes
        return ratemap

    def fit(
        self,
        X,
        y,
        *,
        lengths=None,
        dt=None,
        unit_ids=None,
        n_bins=None,
        sample_weight=None,
    ):
        """Fit Gaussian Naive Bayes according to X, y

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training vectors, where n_samples is the number of samples
            and n_features is the number of features.
                OR
            nelpy.core.BinnedEventArray / BinnedSpikeTrainArray
                The number of spikes in each time bin for each neuron/unit.
        y : array-like, shape (n_samples, n_output_dims)
            Target values.
                OR
            nelpy.core.RegularlySampledAnalogSignalArray
                containing the target values corresponding to X.
            NOTE: If X is an array-like, then y must be an array-like.
        lengths : array-like, shape (n_epochs,), optional (default=None)
            Lengths (in samples) of contiguous segments in (X, y).
            .. versionadded:: x.xx
                BayesianDecoder does not yet support *lengths*.
        unit_ids : array-like, shape (n_units,), optional (default=None)
            Persistent unit IDs that are used to associate units after
            permutation. Unit IDs are inherited from nelpy.core.BinnedEventArray
            objects, or initialized to np.arange(n_units).
        sample_weight : array-like, shape (n_samples,), optional (default=None)
            Weights applied to individual samples (1. for unweighted).
            .. versionadded:: x.xx
               BayesianDecoder does not yet support fitting with *sample_weight*.
        Returns
        -------
        self : object

        """

        # TODO dt should probably come from datawindow specification, but may be overridden here!

        unit_ids = self._check_unit_ids(X=X, unit_ids=unit_ids, fit=True)

        # estimate the firing rate(s):
        self.rate_estimator.fit(X=X, y=y, dt=dt, n_bins=n_bins)

        # store the estimated firing rates as a rate map:
        bin_centers = self.rate_estimator.tc_.bin_centers  # temp code FIXME
        # bins = self.rate_estimator.tc_.bins  # temp code FIXME
        rates = self.rate_estimator.tc_.ratemap  # temp code FIXME
        # unit_ids = np.array(self.rate_estimator.tc_.unit_ids) #temp code FIXME
        self.ratemap.fit(X=bin_centers, y=rates, unit_ids=unit_ids)  # temp code FIXME

        X, y = self._check_X_y(
            X, y, method="fit", lengths=lengths
        )  # can I remove this? no; it sets the bin width... but maybe we should refactor...
        self.ratemap_ = self.ratemap.ratemap_

    def predict(
        self, X, *, output=None, mode="mean", lengths=None, unit_ids=None, dt=None
    ):
        # if output is 'asa', then return an ASA
        check_is_fitted(self, "ratemap_")
        unit_ids = self._check_unit_ids(X=X, unit_ids=unit_ids)
        ratemap = self._get_transformed_ratemap(unit_ids)
        X, dt = self._check_X_dt(X=X, lengths=lengths, dt=dt)

        posterior, mean_pth = decode_bayesian_memoryless_nd(
            X=X, ratemap=ratemap.ratemap_, dt=dt, bin_centers=ratemap.bin_centers
        )

        if output is not None:
            raise NotImplementedError("output mode not implemented yet")
        return posterior, mean_pth

    def predict_proba(self, X, *, lengths=None, unit_ids=None, dt=None):
        check_is_fitted(self, "ratemap_")
        raise NotImplementedError
        ratemap = self._get_transformed_ratemap(unit_ids)
        return self._predict_proba_from_ratemap(X, ratemap)

    def score(self, X, y, *, lengths=None, unit_ids=None, dt=None):
        # check that unit_ids are valid
        # THEN, transform X, y into standardized form (including trimming and permutation) and continue with scoring

        check_is_fitted(self, "ratemap_")
        unit_ids = self._check_unit_ids(X=X, unit_ids=unit_ids)
        ratemap = self._get_transformed_ratemap(unit_ids)
        # X = self._permute_unit_order(X)
        # X, y = self._check_X_y(X, y, method='score', unit_ids=unit_ids)

        raise NotImplementedError
        ratemap = self._get_transformed_ratemap(unit_ids)
        return self._score_from_ratemap(X, ratemap)

    def score_samples(self, X, y, *, lengths=None, unit_ids=None, dt=None):
        # X = self._permute_unit_order(X)
        check_is_fitted(self, "ratemap_")
        raise NotImplementedError

    @property
    def unit_ids(self):
        check_is_fitted(self, "ratemap_")
        return self.ratemap.unit_ids

    @property
    def n_units(self):
        check_is_fitted(self, "ratemap_")
        return len(self.unit_ids)

fit(X, y, *, lengths=None, dt=None, unit_ids=None, n_bins=None, sample_weight=None)

Fit Gaussian Naive Bayes according to X, y

Parameters:

Name Type Description Default
X (array - like, shape(n_samples, n_features))

Training vectors, where n_samples is the number of samples and n_features is the number of features. OR nelpy.core.BinnedEventArray / BinnedSpikeTrainArray The number of spikes in each time bin for each neuron/unit.

required
y (array - like, shape(n_samples, n_output_dims))

Target values. OR nelpy.core.RegularlySampledAnalogSignalArray containing the target values corresponding to X. NOTE: If X is an array-like, then y must be an array-like.

required
lengths (array - like, shape(n_epochs), optional(default=None))

Lengths (in samples) of contiguous segments in (X, y). .. versionadded:: x.xx BayesianDecoder does not yet support lengths.

None
unit_ids (array - like, shape(n_units), optional(default=None))

Persistent unit IDs that are used to associate units after permutation. Unit IDs are inherited from nelpy.core.BinnedEventArray objects, or initialized to np.arange(n_units).

None
sample_weight (array - like, shape(n_samples), optional(default=None))

Weights applied to individual samples (1. for unweighted). .. versionadded:: x.xx BayesianDecoder does not yet support fitting with sample_weight.

None

Returns:

Name Type Description
self object
Source code in nelpy/estimators.py
 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
def fit(
    self,
    X,
    y,
    *,
    lengths=None,
    dt=None,
    unit_ids=None,
    n_bins=None,
    sample_weight=None,
):
    """Fit Gaussian Naive Bayes according to X, y

    Parameters
    ----------
    X : array-like, shape (n_samples, n_features)
        Training vectors, where n_samples is the number of samples
        and n_features is the number of features.
            OR
        nelpy.core.BinnedEventArray / BinnedSpikeTrainArray
            The number of spikes in each time bin for each neuron/unit.
    y : array-like, shape (n_samples, n_output_dims)
        Target values.
            OR
        nelpy.core.RegularlySampledAnalogSignalArray
            containing the target values corresponding to X.
        NOTE: If X is an array-like, then y must be an array-like.
    lengths : array-like, shape (n_epochs,), optional (default=None)
        Lengths (in samples) of contiguous segments in (X, y).
        .. versionadded:: x.xx
            BayesianDecoder does not yet support *lengths*.
    unit_ids : array-like, shape (n_units,), optional (default=None)
        Persistent unit IDs that are used to associate units after
        permutation. Unit IDs are inherited from nelpy.core.BinnedEventArray
        objects, or initialized to np.arange(n_units).
    sample_weight : array-like, shape (n_samples,), optional (default=None)
        Weights applied to individual samples (1. for unweighted).
        .. versionadded:: x.xx
           BayesianDecoder does not yet support fitting with *sample_weight*.
    Returns
    -------
    self : object

    """

    # TODO dt should probably come from datawindow specification, but may be overridden here!

    unit_ids = self._check_unit_ids(X=X, unit_ids=unit_ids, fit=True)

    # estimate the firing rate(s):
    self.rate_estimator.fit(X=X, y=y, dt=dt, n_bins=n_bins)

    # store the estimated firing rates as a rate map:
    bin_centers = self.rate_estimator.tc_.bin_centers  # temp code FIXME
    # bins = self.rate_estimator.tc_.bins  # temp code FIXME
    rates = self.rate_estimator.tc_.ratemap  # temp code FIXME
    # unit_ids = np.array(self.rate_estimator.tc_.unit_ids) #temp code FIXME
    self.ratemap.fit(X=bin_centers, y=rates, unit_ids=unit_ids)  # temp code FIXME

    X, y = self._check_X_y(
        X, y, method="fit", lengths=lengths
    )  # can I remove this? no; it sets the bin width... but maybe we should refactor...
    self.ratemap_ = self.ratemap.ratemap_

FiringRateEstimator

Bases: BaseEstimator

FiringRateEstimator Estimate the firing rate of a spike train.

Parameters:

Name Type Description Default
mode (hist, glm - poisson, glm - binomial, glm, gvm, bars, gp)

The estimation mode. Default is 'hist'. - 'hist': Histogram-based estimation. - 'glm-poisson': Generalized linear model with Poisson distribution. - 'glm-binomial': Generalized linear model with Binomial distribution. - 'glm': Generalized linear model. - 'gvm': Generalized von Mises. - 'bars': Bayesian adaptive regression splines. - 'gp': Gaussian process.

'hist'

Attributes:

Name Type Description
mode str

The estimation mode.

tc_ TuningCurve1D or TuningCurve2D

The estimated tuning curve.

Source code in nelpy/estimators.py
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
class FiringRateEstimator(BaseEstimator):
    """
    FiringRateEstimator
    Estimate the firing rate of a spike train.

    Parameters
    ----------
    mode : {'hist', 'glm-poisson', 'glm-binomial', 'glm', 'gvm', 'bars', 'gp'}, optional
        The estimation mode. Default is 'hist'.
        - 'hist': Histogram-based estimation.
        - 'glm-poisson': Generalized linear model with Poisson distribution.
        - 'glm-binomial': Generalized linear model with Binomial distribution.
        - 'glm': Generalized linear model.
        - 'gvm': Generalized von Mises.
        - 'bars': Bayesian adaptive regression splines.
        - 'gp': Gaussian process.

    Attributes
    ----------
    mode : str
        The estimation mode.
    tc_ : TuningCurve1D or TuningCurve2D
        The estimated tuning curve.
    """

    def __init__(self, mode="hist"):
        """
        Initialize a FiringRateEstimator.

        Parameters
        ----------
        mode : str, optional
            The estimation mode. Default is 'hist'.
        """
        if mode not in ["hist"]:
            raise NotImplementedError(
                "mode '{}' not supported / implemented yet!".format(mode)
            )
        self._mode = mode

    def _check_X_y_dt(self, X, y, lengths=None, dt=None, timestamps=None, n_bins=None):
        """
        Validate and standardize input data for fitting or prediction.

        Parameters
        ----------
        X : array-like or BinnedEventArray
            Input data.
        y : array-like or RegularlySampledAnalogSignalArray
            Target values.
        lengths : array-like, optional
            Lengths of intervals.
        dt : float, optional
            Temporal bin size.
        timestamps : array-like, optional
            Timestamps for the data.
        n_bins : int or array-like, optional
            Number of bins for discretization.

        Returns
        -------
        X : np.ndarray
            Standardized input data.
        y : np.ndarray
            Standardized target values.
        dt : float
            Temporal bin size.
        n_bins : int or array-like
            Number of bins for discretization.
        """
        if isinstance(X, core.BinnedEventArray):
            T = X.bin_centers
            if lengths is not None:
                logging.warning(
                    "'lengths' was passed in, but will be"
                    " overwritten by 'X's 'lengths' attribute"
                )
            if timestamps is not None:
                logging.warning(
                    "'timestamps' was passed in, but will be"
                    " overwritten by 'X's 'bin_centers' attribute"
                )
            if dt is not None:
                logging.warning(
                    "'dt' was passed in, but will be overwritten by 'X's 'ds' attribute"
                )
            if isinstance(y, core.RegularlySampledAnalogSignalArray):
                y = y(T).T

            dt = X.ds
            lengths = X.lengths
            X = X.data.T
        elif isinstance(X, np.ndarray):
            if dt is None:
                raise ValueError(
                    "'dt' is a required argument when 'X' is passed in as a numpy array!"
                )
            if isinstance(y, core.RegularlySampledAnalogSignalArray):
                if timestamps is not None:
                    y = y(timestamps).T
                else:
                    raise ValueError(
                        "'timestamps' required when passing in 'X' as a numpy array and 'y' as a nelpy RegularlySampledAnalogSignalArray!"
                    )
        else:
            raise TypeError(
                "'X' should be either a nelpy BinnedEventArray, or a numpy array!"
            )

        n_samples, n_units = X.shape
        _, n_dims = y.shape
        print("{}-dimensional y passed in".format(n_dims))

        assert n_samples == len(y), (
            "'X' and 'y' must have the same number"
            " of samples! len(X)=={} but len(y)=={}".format(n_samples, len(y))
        )
        if n_bins is not None:
            n_bins = np.atleast_1d(n_bins)
            assert len(n_bins) == n_dims, (
                "'n_bins' must have one entry for each dimension in 'y'!"
            )

        return X, y, dt, n_bins

    def fit(
        self,
        X,
        y,
        lengths=None,
        dt=None,
        timestamps=None,
        unit_ids=None,
        n_bins=None,
        sample_weight=None,
    ):
        """
        Fit the firing rate estimator to the data.

        Parameters
        ----------
        X : array-like
            Input data.
        y : array-like
            Target values.
        lengths : array-like, optional
            Lengths of intervals.
        dt : float, optional
            Temporal bin size.
        timestamps : array-like, optional
            Timestamps for the data.
        unit_ids : array-like, optional
            Unit identifiers.
        n_bins : int or array-like, optional
            Number of bins for discretization.
        sample_weight : array-like, optional
            Weights for each sample.

        Returns
        -------
        self : FiringRateEstimator
            The fitted estimator.
        """
        X, y, dt, n_bins = self._check_X_y_dt(
            X=X, y=y, lengths=lengths, dt=dt, timestamps=timestamps, n_bins=n_bins
        )

        # 1. estimate mask
        # 2. estimate occupancy
        # 3. compute spikes histogram
        # 4. normalize spike histogram by occupancy
        # 5. apply mask

        # if y.n_signals == 1:
        #     self.tc_ = TuningCurve1D(bst=X, extern=y, n_extern=100, extmin=y.min(), extmax=y.max(), sigma=2.5, min_duration=0)
        # if y.n_signals == 2:
        #     xmin, ymin = y.min()
        #     xmax, ymax = y.max()
        #     self.tc_ = TuningCurve2D(bst=X, extern=y, ext_nx=50, ext_ny=50, ext_xmin=xmin, ext_xmax=xmax, ext_ymin=ymin, ext_ymax=ymax, sigma=2.5, min_duration=0)

    @property
    def mode(self):
        return self._mode

    def predict(self, X, lengths=None):
        """
        Predict firing rates for the given input data.

        Parameters
        ----------
        X : array-like
            Input data.
        lengths : array-like, optional
            Lengths of intervals.

        Returns
        -------
        rates : array-like
            Predicted firing rates.
        """
        raise NotImplementedError

    def predict_proba(self, X, lengths=None):
        """
        Predict firing rate probabilities for the given input data.

        Parameters
        ----------
        X : array-like
            Input data.
        lengths : array-like, optional
            Lengths of intervals.

        Returns
        -------
        probabilities : array-like
            Predicted probabilities.
        """
        raise NotImplementedError

    def score(self, X, y, lengths=None):
        """
        Return the mean accuracy on the given test data and labels.

        Parameters
        ----------
        X : array-like
            Test samples.
        y : array-like
            True values for X.
        lengths : array-like, optional
            Lengths of intervals.

        Returns
        -------
        score : float
            Mean accuracy of self.predict(X) wrt. y.
        """
        raise NotImplementedError

    def score_samples(self, X, y, lengths=None):
        """
        Return the per-sample accuracy on the given test data and labels.

        Parameters
        ----------
        X : array-like
            Test samples.
        y : array-like
            True values for X.
        lengths : array-like, optional
            Lengths of intervals.

        Returns
        -------
        scores : array-like
            Per-sample accuracy of self.predict(X) wrt. y.
        """
        raise NotImplementedError

fit(X, y, lengths=None, dt=None, timestamps=None, unit_ids=None, n_bins=None, sample_weight=None)

Fit the firing rate estimator to the data.

Parameters:

Name Type Description Default
X array - like

Input data.

required
y array - like

Target values.

required
lengths array - like

Lengths of intervals.

None
dt float

Temporal bin size.

None
timestamps array - like

Timestamps for the data.

None
unit_ids array - like

Unit identifiers.

None
n_bins int or array - like

Number of bins for discretization.

None
sample_weight array - like

Weights for each sample.

None

Returns:

Name Type Description
self FiringRateEstimator

The fitted estimator.

Source code in nelpy/estimators.py
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
def fit(
    self,
    X,
    y,
    lengths=None,
    dt=None,
    timestamps=None,
    unit_ids=None,
    n_bins=None,
    sample_weight=None,
):
    """
    Fit the firing rate estimator to the data.

    Parameters
    ----------
    X : array-like
        Input data.
    y : array-like
        Target values.
    lengths : array-like, optional
        Lengths of intervals.
    dt : float, optional
        Temporal bin size.
    timestamps : array-like, optional
        Timestamps for the data.
    unit_ids : array-like, optional
        Unit identifiers.
    n_bins : int or array-like, optional
        Number of bins for discretization.
    sample_weight : array-like, optional
        Weights for each sample.

    Returns
    -------
    self : FiringRateEstimator
        The fitted estimator.
    """
    X, y, dt, n_bins = self._check_X_y_dt(
        X=X, y=y, lengths=lengths, dt=dt, timestamps=timestamps, n_bins=n_bins
    )

predict(X, lengths=None)

Predict firing rates for the given input data.

Parameters:

Name Type Description Default
X array - like

Input data.

required
lengths array - like

Lengths of intervals.

None

Returns:

Name Type Description
rates array - like

Predicted firing rates.

Source code in nelpy/estimators.py
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
def predict(self, X, lengths=None):
    """
    Predict firing rates for the given input data.

    Parameters
    ----------
    X : array-like
        Input data.
    lengths : array-like, optional
        Lengths of intervals.

    Returns
    -------
    rates : array-like
        Predicted firing rates.
    """
    raise NotImplementedError

predict_proba(X, lengths=None)

Predict firing rate probabilities for the given input data.

Parameters:

Name Type Description Default
X array - like

Input data.

required
lengths array - like

Lengths of intervals.

None

Returns:

Name Type Description
probabilities array - like

Predicted probabilities.

Source code in nelpy/estimators.py
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
def predict_proba(self, X, lengths=None):
    """
    Predict firing rate probabilities for the given input data.

    Parameters
    ----------
    X : array-like
        Input data.
    lengths : array-like, optional
        Lengths of intervals.

    Returns
    -------
    probabilities : array-like
        Predicted probabilities.
    """
    raise NotImplementedError

score(X, y, lengths=None)

Return the mean accuracy on the given test data and labels.

Parameters:

Name Type Description Default
X array - like

Test samples.

required
y array - like

True values for X.

required
lengths array - like

Lengths of intervals.

None

Returns:

Name Type Description
score float

Mean accuracy of self.predict(X) wrt. y.

Source code in nelpy/estimators.py
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
def score(self, X, y, lengths=None):
    """
    Return the mean accuracy on the given test data and labels.

    Parameters
    ----------
    X : array-like
        Test samples.
    y : array-like
        True values for X.
    lengths : array-like, optional
        Lengths of intervals.

    Returns
    -------
    score : float
        Mean accuracy of self.predict(X) wrt. y.
    """
    raise NotImplementedError

score_samples(X, y, lengths=None)

Return the per-sample accuracy on the given test data and labels.

Parameters:

Name Type Description Default
X array - like

Test samples.

required
y array - like

True values for X.

required
lengths array - like

Lengths of intervals.

None

Returns:

Name Type Description
scores array - like

Per-sample accuracy of self.predict(X) wrt. y.

Source code in nelpy/estimators.py
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
def score_samples(self, X, y, lengths=None):
    """
    Return the per-sample accuracy on the given test data and labels.

    Parameters
    ----------
    X : array-like
        Test samples.
    y : array-like
        True values for X.
    lengths : array-like, optional
        Lengths of intervals.

    Returns
    -------
    scores : array-like
        Per-sample accuracy of self.predict(X) wrt. y.
    """
    raise NotImplementedError

ItemGetter_iloc

Bases: object

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

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

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

Source code in nelpy/estimators.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
class ItemGetter_iloc(object):
    """.iloc is primarily integer position based (from 0 to length-1
    of the axis).

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

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

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

    def __getitem__(self, idx):
        """intervals, series"""
        unit_idx_list = idx
        if isinstance(idx, int):
            unit_idx_list = [idx]

        return self.obj[unit_idx_list]

ItemGetter_loc

Bases: object

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

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

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

Source code in nelpy/estimators.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
class ItemGetter_loc(object):
    """.loc is primarily label based (that is, unit_id based)

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

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

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

    def __getitem__(self, idx):
        """unit_ids"""
        unit_idx_list = self.obj._slicer[idx]

        return self.obj[unit_idx_list]

KeywordError

Bases: Exception

Exception raised for errors in keyword arguments.

Parameters:

Name Type Description Default
message str

Explanation of the error.

required
Source code in nelpy/estimators.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class KeywordError(Exception):
    """
    Exception raised for errors in keyword arguments.

    Parameters
    ----------
    message : str
        Explanation of the error.
    """

    def __init__(self, message):
        """
        Initialize the KeywordError.

        Parameters
        ----------
        message : str
            Explanation of the error.
        """
        self.message = message

NDRateMap

Bases: BaseEstimator

NDRateMap with persistent unit_ids and firing rates in Hz for N-dimensional data.

Parameters:

Name Type Description Default
connectivity (continuous, discrete, circular)

Defines how smoothing is applied. Default is 'continuous'. - 'continuous': Continuous smoothing. - 'discrete': No smoothing is applied. - 'circular': Circular smoothing (for angular variables).

'continuous'

Attributes:

Name Type Description
connectivity str

Smoothing mode.

ratemap_ ndarray

The estimated firing rate map.

_unit_ids ndarray

Persistent unit IDs.

_bins ndarray

Bin edges for each dimension.

_bin_centers ndarray

Bin centers for each dimension.

_mask ndarray

Mask for valid regions.

Source code in nelpy/estimators.py
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
class NDRateMap(BaseEstimator):
    """
    NDRateMap with persistent unit_ids and firing rates in Hz for N-dimensional data.

    Parameters
    ----------
    connectivity : {'continuous', 'discrete', 'circular'}, optional
        Defines how smoothing is applied. Default is 'continuous'.
        - 'continuous': Continuous smoothing.
        - 'discrete': No smoothing is applied.
        - 'circular': Circular smoothing (for angular variables).

    Attributes
    ----------
    connectivity : str
        Smoothing mode.
    ratemap_ : np.ndarray
        The estimated firing rate map.
    _unit_ids : np.ndarray
        Persistent unit IDs.
    _bins : np.ndarray
        Bin edges for each dimension.
    _bin_centers : np.ndarray
        Bin centers for each dimension.
    _mask : np.ndarray
        Mask for valid regions.
    """

    def __init__(self, connectivity="continuous"):
        self.connectivity = connectivity

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

    def __repr__(self):
        r = super().__repr__()
        if self._is_fitted():
            dimstr = ""
            for dd in range(self.n_dims):
                dimstr += ", n_bins_d{}={}".format(dd + 1, self.shape[dd + 1])
            r += " with shape (n_units={}{})".format(self.n_units, dimstr)
        return r

    def fit(self, X, y, dt=1, unit_ids=None):
        """
        Fit firing rates to the provided data.

        Parameters
        ----------
        X : array-like, with shape (n_dims, ), each element of which has
            shape (n_bins_dn, ) for n=1, ..., N; N=n_dims.
            Bin locations (centers) where ratemap is defined.
        y : array-like, shape (n_units, n_bins_d1, ..., n_bins_dN)
            Expected number of spikes in a temporal bin of width dt, for each of
            the predictor bins specified in X.
        dt : float, optional
            Temporal bin size with which firing rate y is defined. Default is 1.
        unit_ids : array-like, shape (n_units,), optional
            Persistent unit IDs that are used to associate units after
            permutation. If None, uses np.arange(n_units).

        Returns
        -------
        self : NDRateMap
            The fitted NDRateMap instance.
        """
        n_units, n_bins, n_dims = self._check_X_y(X, y)

        self.ratemap_ = y / dt
        self._bin_centers = X
        self._bins = np.array(n_dims * [None])

        if n_dims > 1:
            for dd in range(n_dims):
                bin_centers = np.squeeze(X[dd])
                dx = np.median(np.diff(bin_centers))
                bins = np.insert(
                    bin_centers[-1] + np.diff(bin_centers) / 2,
                    0,
                    bin_centers[0] - dx / 2,
                )
                bins = np.append(bins, bins[-1] + dx)
                self._bins[dd] = bins
        else:
            bin_centers = np.squeeze(X)
            dx = np.median(np.diff(bin_centers))
            bins = np.insert(
                bin_centers[-1] + np.diff(bin_centers) / 2, 0, bin_centers[0] - dx / 2
            )
            bins = np.append(bins, bins[-1] + dx)
            self._bins = bins

        if unit_ids is not None:
            if len(unit_ids) != n_units:
                raise ValueError(
                    "'unit_ids' must have same number of elements as 'n_units'. {} != {}".format(
                        len(unit_ids), n_units
                    )
                )
            self._unit_ids = unit_ids
        else:
            self._unit_ids = np.arange(n_units)

    def predict(self, X):
        """
        Predict firing rates for the given bin locations.

        Parameters
        ----------
        X : array-like
            Bin locations to predict firing rates for.

        Returns
        -------
        rates : array-like
            Predicted firing rates.
        """
        check_is_fitted(self, "ratemap_")
        raise NotImplementedError

    def synthesize(self, X):
        """
        Generate synthetic spike data based on the ratemap.

        Parameters
        ----------
        X : array-like
            Bin locations to synthesize spikes for.

        Returns
        -------
        spikes : array-like
            Synthetic spike data.
        """
        check_is_fitted(self, "ratemap_")
        raise NotImplementedError

    def __len__(self):
        return self.n_units

    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_[tuple([index])]
        out._unit_ids = self._unit_ids[index]
        self._index += 1
        return out

    def __getitem__(self, *idx):
        """
        Access RateMap units by index.

        Parameters
        ----------
        *idx : int, slice, or list
            Indices of units to access.

        Returns
        -------
        out : NDRateMap
            Subset NDRateMap with selected units.
        """
        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]

        try:
            out = copy.copy(self)
            out.ratemap_ = self.ratemap_[tuple([idx])]
            out._unit_ids = list(np.array(out._unit_ids)[tuple([idx])])
            out._slicer = UnitSlicer(out)
            out.loc = ItemGetter_loc(out)
            out.iloc = ItemGetter_iloc(out)
            return out
        except Exception:
            raise TypeError("unsupported subsctipting type {}".format(type(idx)))

    def get_peak_firing_order_ids(self):
        """Get the unit_ids in order of peak firing location for 1D RateMaps.

        Returns
        -------
        unit_ids : array-like
            The permutaiton of unit_ids such that after reordering, the peak
            firing locations are ordered along the RateMap.
        """
        check_is_fitted(self, "ratemap_")
        if self.is_2d:
            raise NotImplementedError(
                "get_peak_firing_order_ids() only implemented for 1D RateMaps."
            )
        peakorder = np.argmax(self.ratemap_, axis=1).argsort()
        return np.array(self.unit_ids)[peakorder]

    def reorder_units_by_ids(self, unit_ids, inplace=False):
        """Permute the unit ordering.

        #TODO
        If no order is specified, and an ordering exists from fit(), then the
        data in X will automatically be permuted to match that registered during
        fit().

        Parameters
        ----------
        unit_ids : array-like, shape (n_units,)

        Returns
        -------
        out : reordered RateMap
        """

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

        self._validate_unit_ids(unit_ids)
        if len(unit_ids) != len(self._unit_ids):
            raise ValueError(
                "unit_ids must be a permutation of self.unit_ids, not a subset thereof."
            )

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

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

        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],
            )
            oldorder[frm], oldorder[to] = oldorder[to], oldorder[frm]
        return out

    def _check_X_y(self, X, y):
        y = np.atleast_2d(y)

        n_units = y.shape[0]
        n_bins = y.shape[1:]
        n_dims = len(n_bins)

        if n_dims > 1:
            n_x_bins = tuple([len(x) for x in X])
        else:
            n_x_bins = tuple([len(X)])

        assert n_units > 0, "n_units must be a positive integer!"
        assert n_x_bins == n_bins, "X and y must have the same number of bins!"

        return n_units, n_bins, n_dims

    def _validate_unit_ids(self, unit_ids):
        self._check_unit_ids_in_ratemap(unit_ids)

        if len(set(unit_ids)) != len(unit_ids):
            raise ValueError("Duplicate unit_ids are not allowed.")

    def _check_unit_ids_in_ratemap(self, unit_ids):
        for unit_id in unit_ids:
            # NOTE: the check below allows for predict() to pass on only
            # a subset of the units that were used during fit! So we
            # could fit on 100 units, and then predict on only 10 of
            # them, if we wanted.
            if unit_id not in self.unit_ids:
                raise ValueError(
                    "unit_id {} was not present during fit(); aborting...".format(
                        unit_id
                    )
                )

    def _is_fitted(self):
        try:
            check_is_fitted(self, "ratemap_")
        except Exception:  # should really be except NotFitterError
            return False
        return True

    @property
    def connectivity(self):
        return self._connectivity

    @connectivity.setter
    def connectivity(self, val):
        self._connectivity = self._validate_connectivity(val)

    @staticmethod
    def _validate_connectivity(connectivity):
        connectivity = str(connectivity).strip().lower()
        options = ["continuous", "discrete", "circular"]
        if connectivity in options:
            return connectivity
        raise NotImplementedError(
            "connectivity '{}' is not supported yet!".format(str(connectivity))
        )

    @property
    def shape(self):
        """
        RateMap.shape = (n_units, n_features_x, n_features_y)
            OR
        RateMap.shape = (n_units, n_features)
        """
        check_is_fitted(self, "ratemap_")
        return self.ratemap_.shape

    @property
    def n_dims(self):
        check_is_fitted(self, "ratemap_")
        n_dims = len(self.shape) - 1
        return n_dims

    @property
    def is_1d(self):
        check_is_fitted(self, "ratemap_")
        if len(self.ratemap_.shape) == 2:
            return True
        return False

    @property
    def is_2d(self):
        check_is_fitted(self, "ratemap_")
        if len(self.ratemap_.shape) == 3:
            return True
        return False

    @property
    def n_units(self):
        check_is_fitted(self, "ratemap_")
        return self.ratemap_.shape[0]

    @property
    def unit_ids(self):
        check_is_fitted(self, "ratemap_")
        return self._unit_ids

    @property
    def n_bins(self):
        """(int) Number of external correlates (bins) along each dimension."""
        check_is_fitted(self, "ratemap_")
        if self.n_dims > 1:
            n_bins = tuple([len(x) for x in self.bin_centers])
        else:
            n_bins = len(self.bin_centers)
        return n_bins

    def max(self, axis=None, out=None):
        """
        maximum firing rate for each unit:
            RateMap.max()
        maximum firing rate across units:
            RateMap.max(axis=0)
        """
        raise NotImplementedError("the code was still for the 1D and 2D only version")
        check_is_fitted(self, "ratemap_")
        if axis is None:
            if self.is_2d:
                return self.ratemap_.max(axis=1, out=out).max(axis=1, out=out)
            else:
                return self.ratemap_.max(axis=1, out=out)
        return self.ratemap_.max(axis=axis, out=out)

    def min(self, axis=None, out=None):
        raise NotImplementedError("the code was still for the 1D and 2D only version")
        check_is_fitted(self, "ratemap_")
        if axis is None:
            if self.is_2d:
                return self.ratemap_.min(axis=1, out=out).min(axis=1, out=out)
            else:
                return self.ratemap_.min(axis=1, out=out)
        return self.ratemap_.min(axis=axis, out=out)

    def mean(self, axis=None, dtype=None, out=None, keepdims=False):
        raise NotImplementedError("the code was still for the 1D and 2D only version")
        check_is_fitted(self, "ratemap_")
        kwargs = {"dtype": dtype, "out": out, "keepdims": keepdims}
        if axis is None:
            if self.is_2d:
                return self.ratemap_.mean(axis=1, **kwargs).mean(axis=1, **kwargs)
            else:
                return self.ratemap_.mean(axis=1, **kwargs)
        return self.ratemap_.mean(axis=axis, **kwargs)

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

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

    @property
    def mask(self):
        return self._mask

    @mask.setter
    def mask(self, val):
        # TODO: mask validation
        raise NotImplementedError
        self._mask = val

    def plot(self, **kwargs):
        check_is_fitted(self, "ratemap_")
        if self.is_2d:
            raise NotImplementedError("plot() not yet implemented for 2D RateMaps.")
        pad = kwargs.pop("pad", None)
        _plot_ratemap(self, pad=pad, **kwargs)

    @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'
        truncate : float
            Truncate the filter at this many standard deviations. Default is 4.0.
        truncate : float, deprecated
            Truncate the filter at this many standard deviations. Default is 4.0.
        cval : scalar, optional
            Value to fill past edges of input if mode is 'constant'. Default is 0.0
        """

        raise NotImplementedError

        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

n_bins property

(int) Number of external correlates (bins) along each dimension.

shape property

RateMap.shape = (n_units, n_features_x, n_features_y) OR RateMap.shape = (n_units, n_features)

fit(X, y, dt=1, unit_ids=None)

Fit firing rates to the provided data.

Parameters:

Name Type Description Default
X array-like, with shape (n_dims, ), each element of which has

shape (n_bins_dn, ) for n=1, ..., N; N=n_dims. Bin locations (centers) where ratemap is defined.

required
y (array - like, shape(n_units, n_bins_d1, ..., n_bins_dN))

Expected number of spikes in a temporal bin of width dt, for each of the predictor bins specified in X.

required
dt float

Temporal bin size with which firing rate y is defined. Default is 1.

1
unit_ids (array - like, shape(n_units))

Persistent unit IDs that are used to associate units after permutation. If None, uses np.arange(n_units).

None

Returns:

Name Type Description
self NDRateMap

The fitted NDRateMap instance.

Source code in nelpy/estimators.py
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
def fit(self, X, y, dt=1, unit_ids=None):
    """
    Fit firing rates to the provided data.

    Parameters
    ----------
    X : array-like, with shape (n_dims, ), each element of which has
        shape (n_bins_dn, ) for n=1, ..., N; N=n_dims.
        Bin locations (centers) where ratemap is defined.
    y : array-like, shape (n_units, n_bins_d1, ..., n_bins_dN)
        Expected number of spikes in a temporal bin of width dt, for each of
        the predictor bins specified in X.
    dt : float, optional
        Temporal bin size with which firing rate y is defined. Default is 1.
    unit_ids : array-like, shape (n_units,), optional
        Persistent unit IDs that are used to associate units after
        permutation. If None, uses np.arange(n_units).

    Returns
    -------
    self : NDRateMap
        The fitted NDRateMap instance.
    """
    n_units, n_bins, n_dims = self._check_X_y(X, y)

    self.ratemap_ = y / dt
    self._bin_centers = X
    self._bins = np.array(n_dims * [None])

    if n_dims > 1:
        for dd in range(n_dims):
            bin_centers = np.squeeze(X[dd])
            dx = np.median(np.diff(bin_centers))
            bins = np.insert(
                bin_centers[-1] + np.diff(bin_centers) / 2,
                0,
                bin_centers[0] - dx / 2,
            )
            bins = np.append(bins, bins[-1] + dx)
            self._bins[dd] = bins
    else:
        bin_centers = np.squeeze(X)
        dx = np.median(np.diff(bin_centers))
        bins = np.insert(
            bin_centers[-1] + np.diff(bin_centers) / 2, 0, bin_centers[0] - dx / 2
        )
        bins = np.append(bins, bins[-1] + dx)
        self._bins = bins

    if unit_ids is not None:
        if len(unit_ids) != n_units:
            raise ValueError(
                "'unit_ids' must have same number of elements as 'n_units'. {} != {}".format(
                    len(unit_ids), n_units
                )
            )
        self._unit_ids = unit_ids
    else:
        self._unit_ids = np.arange(n_units)

get_peak_firing_order_ids()

Get the unit_ids in order of peak firing location for 1D RateMaps.

Returns:

Name Type Description
unit_ids array - like

The permutaiton of unit_ids such that after reordering, the peak firing locations are ordered along the RateMap.

Source code in nelpy/estimators.py
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
def get_peak_firing_order_ids(self):
    """Get the unit_ids in order of peak firing location for 1D RateMaps.

    Returns
    -------
    unit_ids : array-like
        The permutaiton of unit_ids such that after reordering, the peak
        firing locations are ordered along the RateMap.
    """
    check_is_fitted(self, "ratemap_")
    if self.is_2d:
        raise NotImplementedError(
            "get_peak_firing_order_ids() only implemented for 1D RateMaps."
        )
    peakorder = np.argmax(self.ratemap_, axis=1).argsort()
    return np.array(self.unit_ids)[peakorder]

max(axis=None, out=None)

maximum firing rate for each unit: RateMap.max() maximum firing rate across units: RateMap.max(axis=0)

Source code in nelpy/estimators.py
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
def max(self, axis=None, out=None):
    """
    maximum firing rate for each unit:
        RateMap.max()
    maximum firing rate across units:
        RateMap.max(axis=0)
    """
    raise NotImplementedError("the code was still for the 1D and 2D only version")
    check_is_fitted(self, "ratemap_")
    if axis is None:
        if self.is_2d:
            return self.ratemap_.max(axis=1, out=out).max(axis=1, out=out)
        else:
            return self.ratemap_.max(axis=1, out=out)
    return self.ratemap_.max(axis=axis, out=out)

predict(X)

Predict firing rates for the given bin locations.

Parameters:

Name Type Description Default
X array - like

Bin locations to predict firing rates for.

required

Returns:

Name Type Description
rates array - like

Predicted firing rates.

Source code in nelpy/estimators.py
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
def predict(self, X):
    """
    Predict firing rates for the given bin locations.

    Parameters
    ----------
    X : array-like
        Bin locations to predict firing rates for.

    Returns
    -------
    rates : array-like
        Predicted firing rates.
    """
    check_is_fitted(self, "ratemap_")
    raise NotImplementedError

reorder_units_by_ids(unit_ids, inplace=False)

Permute the unit ordering.

TODO

If no order is specified, and an ordering exists from fit(), then the data in X will automatically be permuted to match that registered during fit().

Parameters:

Name Type Description Default
unit_ids (array - like, shape(n_units))
required

Returns:

Name Type Description
out reordered RateMap
Source code in nelpy/estimators.py
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
def reorder_units_by_ids(self, unit_ids, inplace=False):
    """Permute the unit ordering.

    #TODO
    If no order is specified, and an ordering exists from fit(), then the
    data in X will automatically be permuted to match that registered during
    fit().

    Parameters
    ----------
    unit_ids : array-like, shape (n_units,)

    Returns
    -------
    out : reordered RateMap
    """

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

    self._validate_unit_ids(unit_ids)
    if len(unit_ids) != len(self._unit_ids):
        raise ValueError(
            "unit_ids must be a permutation of self.unit_ids, not a subset thereof."
        )

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

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

    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],
        )
        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' truncate : float Truncate the filter at this many standard deviations. Default is 4.0. truncate : float, deprecated Truncate the filter at this many standard deviations. Default is 4.0. cval : scalar, optional Value to fill past edges of input if mode is 'constant'. Default is 0.0

Source code in nelpy/estimators.py
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
@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'
    truncate : float
        Truncate the filter at this many standard deviations. Default is 4.0.
    truncate : float, deprecated
        Truncate the filter at this many standard deviations. Default is 4.0.
    cval : scalar, optional
        Value to fill past edges of input if mode is 'constant'. Default is 0.0
    """

    raise NotImplementedError

    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

synthesize(X)

Generate synthetic spike data based on the ratemap.

Parameters:

Name Type Description Default
X array - like

Bin locations to synthesize spikes for.

required

Returns:

Name Type Description
spikes array - like

Synthetic spike data.

Source code in nelpy/estimators.py
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
def synthesize(self, X):
    """
    Generate synthetic spike data based on the ratemap.

    Parameters
    ----------
    X : array-like
        Bin locations to synthesize spikes for.

    Returns
    -------
    spikes : array-like
        Synthetic spike data.
    """
    check_is_fitted(self, "ratemap_")
    raise NotImplementedError

RateMap

Bases: BaseEstimator

RateMap with persistent unit_ids and firing rates in Hz.

This class estimates and stores firing rate maps for neural data, supporting both 1D and 2D spatial representations.

Parameters:

Name Type Description Default
connectivity (continuous, discrete, circular)

Defines how smoothing is applied. Default is 'continuous'. - 'continuous': Continuous smoothing. - 'discrete': No smoothing is applied. - 'circular': Circular smoothing (for angular variables).

'continuous'

Attributes:

Name Type Description
connectivity str

Smoothing mode.

ratemap_ ndarray

The estimated firing rate map.

_unit_ids ndarray

Persistent unit IDs.

_bins_x, _bins_y ndarray

Bin edges for each dimension.

_bin_centers_x, _bin_centers_y ndarray

Bin centers for each dimension.

_mask ndarray

Mask for valid regions.

Source code in nelpy/estimators.py
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
class RateMap(BaseEstimator):
    """
    RateMap with persistent unit_ids and firing rates in Hz.

    This class estimates and stores firing rate maps for neural data, supporting both 1D and 2D spatial representations.

    Parameters
    ----------
    connectivity : {'continuous', 'discrete', 'circular'}, optional
        Defines how smoothing is applied. Default is 'continuous'.
        - 'continuous': Continuous smoothing.
        - 'discrete': No smoothing is applied.
        - 'circular': Circular smoothing (for angular variables).

    Attributes
    ----------
    connectivity : str
        Smoothing mode.
    ratemap_ : np.ndarray
        The estimated firing rate map.
    _unit_ids : np.ndarray
        Persistent unit IDs.
    _bins_x, _bins_y : np.ndarray
        Bin edges for each dimension.
    _bin_centers_x, _bin_centers_y : np.ndarray
        Bin centers for each dimension.
    _mask : np.ndarray
        Mask for valid regions.
    """

    def __init__(self, connectivity="continuous"):
        """
        Initialize a RateMap object.

        Parameters
        ----------
        connectivity : str, optional
            Defines how smoothing is applied. If 'discrete', then no smoothing is
            applied. Default is 'continuous'.
        """
        self.connectivity = connectivity
        self._slicer = UnitSlicer(self)
        self.loc = ItemGetter_loc(self)
        self.iloc = ItemGetter_iloc(self)

    def __repr__(self):
        """
        Return a string representation of the RateMap, including shape if fitted.

        Returns
        -------
        r : str
            String representation of the RateMap.
        """
        r = super().__repr__()
        if self._is_fitted():
            if self.is_1d:
                r += " with shape (n_units={}, n_bins_x={})".format(*self.shape)
            else:
                r += " with shape (n_units={}, n_bins_x={}, n_bins_y={})".format(
                    *self.shape
                )
        return r

    def fit(self, X, y, dt=1, unit_ids=None):
        """
        Fit firing rates to the provided data.

        Parameters
        ----------
        X : array-like, shape (n_bins,) or (n_bins_x, n_bins_y)
            Bin locations (centers) where ratemap is defined.
        y : array-like, shape (n_units, n_bins) or (n_units, n_bins_x, n_bins_y)
            Expected number of spikes in a temporal bin of width dt, for each of
            the predictor bins specified in X.
        dt : float, optional
            Temporal bin size with which firing rate y is defined. Default is 1.
        unit_ids : array-like, shape (n_units,), optional
            Persistent unit IDs that are used to associate units after
            permutation. If None, uses np.arange(n_units).

        Returns
        -------
        self : RateMap
            The fitted RateMap instance.
        """
        n_units, n_bins_x, n_bins_y = self._check_X_y(X, y)
        if n_bins_y > 0:
            # self.ratemap_ = np.zeros((n_units, n_bins_x, n_bins_y)) #FIXME
            self.ratemap_ = y / dt
            bin_centers_x = np.squeeze(X[:, 0])
            bin_centers_y = np.squeeze(X[:, 1])
            bin_dx = np.median(np.diff(bin_centers_x))
            bin_dy = np.median(np.diff(bin_centers_y))
            bins_x = np.insert(
                bin_centers_x[:-1] + np.diff(bin_centers_x) / 2,
                0,
                bin_centers_x[0] - bin_dx / 2,
            )
            bins_x = np.append(bins_x, bins_x[-1] + bin_dx)
            bins_y = np.insert(
                bin_centers_y[:-1] + np.diff(bin_centers_y) / 2,
                0,
                bin_centers_y[0] - bin_dy / 2,
            )
            bins_y = np.append(bins_y, bins_y[-1] + bin_dy)
            self._bins_x = bins_x
            self._bins_y = bins_y
            self._bin_centers_x = bin_centers_x
            self._bin_centers_y = X[:, 1]
        else:
            # self.ratemap_ = np.zeros((n_units, n_bins_x)) #FIXME
            self.ratemap_ = y / dt
            bin_centers_x = np.squeeze(X)
            bin_dx = np.median(np.diff(bin_centers_x))
            bins_x = np.insert(
                bin_centers_x[:-1] + np.diff(bin_centers_x) / 2,
                0,
                bin_centers_x[0] - bin_dx / 2,
            )
            bins_x = np.append(bins_x, bins_x[-1] + bin_dx)
            self._bins_x = bins_x
            self._bin_centers_x = bin_centers_x

        if unit_ids is not None:
            if len(unit_ids) != n_units:
                raise ValueError(
                    "'unit_ids' must have same number of elements as 'n_units'. {} != {}".format(
                        len(unit_ids), n_units
                    )
                )
            self._unit_ids = unit_ids
        else:
            self._unit_ids = np.arange(n_units)

    def predict(self, X):
        """
        Predict firing rates for the given bin locations.

        Parameters
        ----------
        X : array-like
            Bin locations to predict firing rates for.

        Returns
        -------
        rates : array-like
            Predicted firing rates.
        """
        check_is_fitted(self, "ratemap_")
        raise NotImplementedError

    def synthesize(self, X):
        """
        Generate synthetic spike data based on the ratemap.

        Parameters
        ----------
        X : array-like
            Bin locations to synthesize spikes for.

        Returns
        -------
        spikes : array-like
            Synthetic spike data.
        """
        check_is_fitted(self, "ratemap_")
        raise NotImplementedError

    def __len__(self):
        return self.n_units

    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_[tuple([index])]
        out._unit_ids = self._unit_ids[index]
        self._index += 1
        return out

    def __getitem__(self, *idx):
        """
        Access RateMap units by index.

        Parameters
        ----------
        *idx : int, slice, or list
            Indices of units to access.

        Returns
        -------
        out : RateMap
            Subset RateMap with selected units.
        """
        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]

        try:
            out = copy.copy(self)
            out.ratemap_ = self.ratemap_[tuple([idx])]
            out._unit_ids = list(np.array(out._unit_ids)[tuple([idx])])
            out._slicer = UnitSlicer(out)
            out.loc = ItemGetter_loc(out)
            out.iloc = ItemGetter_iloc(out)
            return out
        except Exception:
            raise TypeError("unsupported subsctipting type {}".format(type(idx)))

    def get_peak_firing_order_ids(self):
        """Get the unit_ids in order of peak firing location for 1D RateMaps.

        Returns
        -------
        unit_ids : array-like
            The permutaiton of unit_ids such that after reordering, the peak
            firing locations are ordered along the RateMap.
        """
        check_is_fitted(self, "ratemap_")
        if self.is_2d:
            raise NotImplementedError(
                "get_peak_firing_order_ids() only implemented for 1D RateMaps."
            )
        peakorder = np.argmax(self.ratemap_, axis=1).argsort()
        return np.array(self.unit_ids)[peakorder]

    def reorder_units_by_ids(self, unit_ids, inplace=False):
        """Permute the unit ordering.

        #TODO
        If no order is specified, and an ordering exists from fit(), then the
        data in X will automatically be permuted to match that registered during
        fit().

        Parameters
        ----------
        unit_ids : array-like, shape (n_units,)

        Returns
        -------
        out : reordered RateMap
        """

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

        self._validate_unit_ids(unit_ids)
        if len(unit_ids) != len(self._unit_ids):
            raise ValueError(
                "unit_ids must be a permutation of self.unit_ids, not a subset thereof."
            )

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

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

        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],
            )
            oldorder[frm], oldorder[to] = oldorder[to], oldorder[frm]
        return out

    def _check_X_y(self, X, y):
        X = np.atleast_1d(X)
        y = np.atleast_2d(y)

        n_units = y.shape[0]
        n_bins_xy = y.shape[1]
        try:
            n_bins_yy = y.shape[2]
        except IndexError:
            n_bins_yy = 0

        n_bins_xx = X.shape[0]
        try:
            n_bins_yx = X.shape[1]
        except IndexError:
            n_bins_yx = 0

        assert n_units > 0, "n_units must be a positive integer!"
        assert n_bins_xx == n_bins_xy, "X and y must have the same n_bins_x"
        assert n_bins_yx == n_bins_yy, "X and y must have the same n_bins_y"

        n_bins_x = n_bins_xx
        n_bins_y = n_bins_yy

        return n_units, n_bins_x, n_bins_y

    def _validate_unit_ids(self, unit_ids):
        self._check_unit_ids_in_ratemap(unit_ids)

        if len(set(unit_ids)) != len(unit_ids):
            raise ValueError("Duplicate unit_ids are not allowed.")

    def _check_unit_ids_in_ratemap(self, unit_ids):
        for unit_id in unit_ids:
            # NOTE: the check below allows for predict() to pass on only
            # a subset of the units that were used during fit! So we
            # could fit on 100 units, and then predict on only 10 of
            # them, if we wanted.
            if unit_id not in self.unit_ids:
                raise ValueError(
                    "unit_id {} was not present during fit(); aborting...".format(
                        unit_id
                    )
                )

    def _is_fitted(self):
        try:
            check_is_fitted(self, "ratemap_")
        except Exception:  # should really be except NotFitterError
            return False
        return True

    @property
    def connectivity(self):
        return self._connectivity

    @connectivity.setter
    def connectivity(self, val):
        self._connectivity = self._validate_connectivity(val)

    @staticmethod
    def _validate_connectivity(connectivity):
        connectivity = str(connectivity).strip().lower()
        options = ["continuous", "discrete", "circular"]
        if connectivity in options:
            return connectivity
        raise NotImplementedError(
            "connectivity '{}' is not supported yet!".format(str(connectivity))
        )

    @staticmethod
    def _units_from_X(X):
        """
        Get unit_ids from bst X, or generate them from ndarray X.

        Returns
        -------
        n_units :
        unit_ids :
        """
        raise NotImplementedError

    @property
    def T(self):
        """transpose the ratemap.
        Here we transpose the x and y dims, and return a new RateMap object.
        """
        if self.is_1d:
            return self
        out = copy.copy(self)
        out.ratemap_ = np.transpose(out.ratemap_, axes=(0, 2, 1))
        return out

    @property
    def shape(self):
        """
        RateMap.shape = (n_units, n_features_x, n_features_y)
            OR
        RateMap.shape = (n_units, n_features)
        """
        check_is_fitted(self, "ratemap_")
        return self.ratemap_.shape

    @property
    def is_1d(self):
        check_is_fitted(self, "ratemap_")
        if len(self.ratemap_.shape) == 2:
            return True
        return False

    @property
    def is_2d(self):
        check_is_fitted(self, "ratemap_")
        if len(self.ratemap_.shape) == 3:
            return True
        return False

    @property
    def n_units(self):
        check_is_fitted(self, "ratemap_")
        return self.ratemap_.shape[0]

    @property
    def unit_ids(self):
        check_is_fitted(self, "ratemap_")
        return self._unit_ids

    @property
    def n_bins(self):
        """(int) Number of external correlates (bins)."""
        check_is_fitted(self, "ratemap_")
        if self.is_2d:
            return self.n_bins_x * self.n_bins_y
        return self.n_bins_x

    @property
    def n_bins_x(self):
        """(int) Number of external correlates (bins)."""
        check_is_fitted(self, "ratemap_")
        return self.ratemap_.shape[1]

    @property
    def n_bins_y(self):
        """(int) Number of external correlates (bins)."""
        check_is_fitted(self, "ratemap_")
        if self.is_1d:
            raise ValueError("RateMap is 1D; no y bins are defined.")
        return self.ratemap_.shape[2]

    def max(self, axis=None, out=None):
        """
        maximum firing rate for each unit:
            RateMap.max()
        maximum firing rate across units:
            RateMap.max(axis=0)
        """
        check_is_fitted(self, "ratemap_")
        if axis is None:
            if self.is_2d:
                return self.ratemap_.max(axis=1, out=out).max(axis=1, out=out)
            else:
                return self.ratemap_.max(axis=1, out=out)
        return self.ratemap_.max(axis=axis, out=out)

    def min(self, axis=None, out=None):
        check_is_fitted(self, "ratemap_")
        if axis is None:
            if self.is_2d:
                return self.ratemap_.min(axis=1, out=out).min(axis=1, out=out)
            else:
                return self.ratemap_.min(axis=1, out=out)
        return self.ratemap_.min(axis=axis, out=out)

    def mean(self, axis=None, dtype=None, out=None, keepdims=False):
        check_is_fitted(self, "ratemap_")
        kwargs = {"dtype": dtype, "out": out, "keepdims": keepdims}
        if axis is None:
            if self.is_2d:
                return self.ratemap_.mean(axis=1, **kwargs).mean(axis=1, **kwargs)
            else:
                return self.ratemap_.mean(axis=1, **kwargs)
        return self.ratemap_.mean(axis=axis, **kwargs)

    @property
    def bins(self):
        if self.is_1d:
            return self._bins_x
        return np.vstack((self._bins_x, self._bins_y))

    @property
    def bins_x(self):
        return self._bins_x

    @property
    def bins_y(self):
        if self.is_2d:
            return self._bins_y
        else:
            raise ValueError("only valid for 2D RateMap() objects.")

    @property
    def bin_centers(self):
        if self.is_1d:
            return self._bin_centers_x
        return np.vstack((self._bin_centers_x, self._bin_centers_y))

    @property
    def bin_centers_x(self):
        return self._bin_centers_x

    @property
    def bin_centers_y(self):
        if self.is_2d:
            return self._bin_centers_y
        else:
            raise ValueError("only valid for 2D RateMap() objects.")

    @property
    def mask(self):
        return self._mask

    @mask.setter
    def mask(self, val):
        # TODO: mask validation
        raise NotImplementedError
        self._mask = val

    def plot(self, **kwargs):
        check_is_fitted(self, "ratemap_")
        if self.is_2d:
            raise NotImplementedError("plot() not yet implemented for 2D RateMaps.")
        pad = kwargs.pop("pad", None)
        _plot_ratemap(self, pad=pad, **kwargs)

    @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’
        truncate : float
            Truncate the filter at this many standard deviations. Default is 4.0.
        truncate : float, deprecated
            Truncate the filter at this many standard deviations. Default is 4.0.
        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

        raise NotImplementedError

T property

transpose the ratemap. Here we transpose the x and y dims, and return a new RateMap object.

n_bins property

(int) Number of external correlates (bins).

n_bins_x property

(int) Number of external correlates (bins).

n_bins_y property

(int) Number of external correlates (bins).

shape property

RateMap.shape = (n_units, n_features_x, n_features_y) OR RateMap.shape = (n_units, n_features)

fit(X, y, dt=1, unit_ids=None)

Fit firing rates to the provided data.

Parameters:

Name Type Description Default
X (array - like, shape(n_bins) or (n_bins_x, n_bins_y))

Bin locations (centers) where ratemap is defined.

required
y (array - like, shape(n_units, n_bins) or (n_units, n_bins_x, n_bins_y))

Expected number of spikes in a temporal bin of width dt, for each of the predictor bins specified in X.

required
dt float

Temporal bin size with which firing rate y is defined. Default is 1.

1
unit_ids (array - like, shape(n_units))

Persistent unit IDs that are used to associate units after permutation. If None, uses np.arange(n_units).

None

Returns:

Name Type Description
self RateMap

The fitted RateMap instance.

Source code in nelpy/estimators.py
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
def fit(self, X, y, dt=1, unit_ids=None):
    """
    Fit firing rates to the provided data.

    Parameters
    ----------
    X : array-like, shape (n_bins,) or (n_bins_x, n_bins_y)
        Bin locations (centers) where ratemap is defined.
    y : array-like, shape (n_units, n_bins) or (n_units, n_bins_x, n_bins_y)
        Expected number of spikes in a temporal bin of width dt, for each of
        the predictor bins specified in X.
    dt : float, optional
        Temporal bin size with which firing rate y is defined. Default is 1.
    unit_ids : array-like, shape (n_units,), optional
        Persistent unit IDs that are used to associate units after
        permutation. If None, uses np.arange(n_units).

    Returns
    -------
    self : RateMap
        The fitted RateMap instance.
    """
    n_units, n_bins_x, n_bins_y = self._check_X_y(X, y)
    if n_bins_y > 0:
        # self.ratemap_ = np.zeros((n_units, n_bins_x, n_bins_y)) #FIXME
        self.ratemap_ = y / dt
        bin_centers_x = np.squeeze(X[:, 0])
        bin_centers_y = np.squeeze(X[:, 1])
        bin_dx = np.median(np.diff(bin_centers_x))
        bin_dy = np.median(np.diff(bin_centers_y))
        bins_x = np.insert(
            bin_centers_x[:-1] + np.diff(bin_centers_x) / 2,
            0,
            bin_centers_x[0] - bin_dx / 2,
        )
        bins_x = np.append(bins_x, bins_x[-1] + bin_dx)
        bins_y = np.insert(
            bin_centers_y[:-1] + np.diff(bin_centers_y) / 2,
            0,
            bin_centers_y[0] - bin_dy / 2,
        )
        bins_y = np.append(bins_y, bins_y[-1] + bin_dy)
        self._bins_x = bins_x
        self._bins_y = bins_y
        self._bin_centers_x = bin_centers_x
        self._bin_centers_y = X[:, 1]
    else:
        # self.ratemap_ = np.zeros((n_units, n_bins_x)) #FIXME
        self.ratemap_ = y / dt
        bin_centers_x = np.squeeze(X)
        bin_dx = np.median(np.diff(bin_centers_x))
        bins_x = np.insert(
            bin_centers_x[:-1] + np.diff(bin_centers_x) / 2,
            0,
            bin_centers_x[0] - bin_dx / 2,
        )
        bins_x = np.append(bins_x, bins_x[-1] + bin_dx)
        self._bins_x = bins_x
        self._bin_centers_x = bin_centers_x

    if unit_ids is not None:
        if len(unit_ids) != n_units:
            raise ValueError(
                "'unit_ids' must have same number of elements as 'n_units'. {} != {}".format(
                    len(unit_ids), n_units
                )
            )
        self._unit_ids = unit_ids
    else:
        self._unit_ids = np.arange(n_units)

get_peak_firing_order_ids()

Get the unit_ids in order of peak firing location for 1D RateMaps.

Returns:

Name Type Description
unit_ids array - like

The permutaiton of unit_ids such that after reordering, the peak firing locations are ordered along the RateMap.

Source code in nelpy/estimators.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
def get_peak_firing_order_ids(self):
    """Get the unit_ids in order of peak firing location for 1D RateMaps.

    Returns
    -------
    unit_ids : array-like
        The permutaiton of unit_ids such that after reordering, the peak
        firing locations are ordered along the RateMap.
    """
    check_is_fitted(self, "ratemap_")
    if self.is_2d:
        raise NotImplementedError(
            "get_peak_firing_order_ids() only implemented for 1D RateMaps."
        )
    peakorder = np.argmax(self.ratemap_, axis=1).argsort()
    return np.array(self.unit_ids)[peakorder]

max(axis=None, out=None)

maximum firing rate for each unit: RateMap.max() maximum firing rate across units: RateMap.max(axis=0)

Source code in nelpy/estimators.py
609
610
611
612
613
614
615
616
617
618
619
620
621
622
def max(self, axis=None, out=None):
    """
    maximum firing rate for each unit:
        RateMap.max()
    maximum firing rate across units:
        RateMap.max(axis=0)
    """
    check_is_fitted(self, "ratemap_")
    if axis is None:
        if self.is_2d:
            return self.ratemap_.max(axis=1, out=out).max(axis=1, out=out)
        else:
            return self.ratemap_.max(axis=1, out=out)
    return self.ratemap_.max(axis=axis, out=out)

predict(X)

Predict firing rates for the given bin locations.

Parameters:

Name Type Description Default
X array - like

Bin locations to predict firing rates for.

required

Returns:

Name Type Description
rates array - like

Predicted firing rates.

Source code in nelpy/estimators.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def predict(self, X):
    """
    Predict firing rates for the given bin locations.

    Parameters
    ----------
    X : array-like
        Bin locations to predict firing rates for.

    Returns
    -------
    rates : array-like
        Predicted firing rates.
    """
    check_is_fitted(self, "ratemap_")
    raise NotImplementedError

reorder_units_by_ids(unit_ids, inplace=False)

Permute the unit ordering.

TODO

If no order is specified, and an ordering exists from fit(), then the data in X will automatically be permuted to match that registered during fit().

Parameters:

Name Type Description Default
unit_ids (array - like, shape(n_units))
required

Returns:

Name Type Description
out reordered RateMap
Source code in nelpy/estimators.py
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
def reorder_units_by_ids(self, unit_ids, inplace=False):
    """Permute the unit ordering.

    #TODO
    If no order is specified, and an ordering exists from fit(), then the
    data in X will automatically be permuted to match that registered during
    fit().

    Parameters
    ----------
    unit_ids : array-like, shape (n_units,)

    Returns
    -------
    out : reordered RateMap
    """

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

    self._validate_unit_ids(unit_ids)
    if len(unit_ids) != len(self._unit_ids):
        raise ValueError(
            "unit_ids must be a permutation of self.unit_ids, not a subset thereof."
        )

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

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

    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],
        )
        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’ truncate : float Truncate the filter at this many standard deviations. Default is 4.0. truncate : float, deprecated Truncate the filter at this many standard deviations. Default is 4.0. cval : scalar, optional Value to fill past edges of input if mode is 'constant'. Default is 0.0

Source code in nelpy/estimators.py
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
@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’
    truncate : float
        Truncate the filter at this many standard deviations. Default is 4.0.
    truncate : float, deprecated
        Truncate the filter at this many standard deviations. Default is 4.0.
    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

    raise NotImplementedError

synthesize(X)

Generate synthetic spike data based on the ratemap.

Parameters:

Name Type Description Default
X array - like

Bin locations to synthesize spikes for.

required

Returns:

Name Type Description
spikes array - like

Synthetic spike data.

Source code in nelpy/estimators.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def synthesize(self, X):
    """
    Generate synthetic spike data based on the ratemap.

    Parameters
    ----------
    X : array-like
        Bin locations to synthesize spikes for.

    Returns
    -------
    spikes : array-like
        Synthetic spike data.
    """
    check_is_fitted(self, "ratemap_")
    raise NotImplementedError

UnitSlicer

Bases: object

Source code in nelpy/estimators.py
 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
class UnitSlicer(object):
    def __init__(self, obj):
        self.obj = obj

    def __getitem__(self, *args):
        """units ids"""
        # by default, keep all units
        unitslice = slice(None, None, None)
        if isinstance(*args, int):
            unitslice = args[0]
        else:
            slices = np.s_[args]
            slices = slices[0]
            unitslice = slices

        if isinstance(unitslice, slice):
            start = unitslice.start
            stop = unitslice.stop
            istep = unitslice.step

            try:
                if start is None:
                    istart = 0
                else:
                    istart = list(self.obj.unit_ids).index(start)
            except ValueError:
                raise KeyError(
                    "unit_id {} could not be found in RateMap!".format(start)
                )

            try:
                if stop is None:
                    istop = self.obj.n_units
                else:
                    istop = list(self.obj.unit_ids).index(stop) + 1
            except ValueError:
                raise KeyError("unit_id {} could not be found in RateMap!".format(stop))
            if istep is None:
                istep = 1
            if istep < 0:
                istop -= 1
                istart -= 1
                istart, istop = istop, istart
            unit_idx_list = list(range(istart, istop, istep))
        else:
            unit_idx_list = []
            unitslice = np.atleast_1d(unitslice)
            for unit in unitslice:
                try:
                    uidx = list(self.obj.unit_ids).index(unit)
                except ValueError:
                    raise KeyError(
                        "unit_id {} could not be found in RateMap!".format(unit)
                    )
                else:
                    unit_idx_list.append(uidx)

        return unit_idx_list

decode_bayesian_memoryless_nd(X, *, ratemap, bin_centers, dt=1)

Memoryless Bayesian decoding (supports multidimensional decoding).

Decode binned spike counts (e.g. from a BinnedSpikeTrainArray) to an external correlate (e.g. position), using a memoryless Bayesian decoder and a previously estimated ratemap.

Parameters:

Name Type Description Default
X numpy array with shape (n_samples, n_features),

where the features are generally putative units / cells, and where each sample represents spike counts in a singleton data window.

required
ratemap array-like of shape (n_units, n_bins_d1, ..., n_bins_dN)

Expected number of spikes for each unit, within each bin, along each dimension.

required
bin_centers array-like with shape (n_dims, ), where each element is also

an array-like with shape (n_bins_dn, ) containing the bin centers for the particular dimension.

required
dt (float, optional(default=1))

Temporal bin width corresponding to X, in seconds.

NOTE: generally it is assumed that ratemap will be given in Hz (that is, it has dt=1). If ratemap has a different unit, then dt might have to be adjusted to compensate for this. This can get tricky / confusing, so the recommended approach is always to construct ratemap with dt=1, and then to use the data-specific dt here when decoding.

1

Returns:

Name Type Description
posterior numpy array of shape (n_samples, n_bins_d1, ..., n_bins_dN)

Posterior probabilities for each voxel.

expected_pth numpy array of shape (n_samples, n_dims)

Expected (posterior-averaged) decoded trajectory.

Source code in nelpy/estimators.py
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
def decode_bayesian_memoryless_nd(X, *, ratemap, bin_centers, dt=1):
    """Memoryless Bayesian decoding (supports multidimensional decoding).

    Decode binned spike counts (e.g. from a BinnedSpikeTrainArray) to an
    external correlate (e.g. position), using a memoryless Bayesian decoder and
    a previously estimated ratemap.

    Parameters
    ----------
    X : numpy array with shape (n_samples, n_features),
        where the features are generally putative units / cells, and where
        each sample represents spike counts in a singleton data window.
    ratemap : array-like of shape (n_units, n_bins_d1, ..., n_bins_dN)
        Expected number of spikes for each unit, within each bin, along each
        dimension.
    bin_centers : array-like with shape (n_dims, ), where each element is also
        an array-like with shape (n_bins_dn, ) containing the bin centers for
        the particular dimension.
    dt : float, optional (default=1)
        Temporal bin width corresponding to X, in seconds.

        NOTE: generally it is assumed that ratemap will be given in Hz (that is,
        it has dt=1). If ratemap has a different unit, then dt might have to be
        adjusted to compensate for this. This can get tricky / confusing, so the
        recommended approach is always to construct ratemap with dt=1, and then
        to use the data-specific dt here when decoding.

    Returns
    -------
    posterior : numpy array of shape (n_samples, n_bins_d1, ..., n_bins_dN)
        Posterior probabilities for each voxel.
    expected_pth : numpy array of shape (n_samples, n_dims)
        Expected (posterior-averaged) decoded trajectory.
    """

    def tile_obs(obs, *n_bins):
        n_units = len(obs)
        out = np.zeros((n_units, *n_bins))
        for unit in range(n_units):
            out[unit, :] = obs[unit]
        return out

    n_samples, n_features = X.shape
    n_units = ratemap.shape[0]
    n_bins = np.atleast_1d(ratemap.shape[1:])
    n_dims = len(n_bins)

    assert n_features == n_units, "X has {} units, whereas ratemap has {}".format(
        n_features, n_units
    )

    lfx = np.log(ratemap)
    eterm = -ratemap.sum(axis=0) * dt

    posterior = np.empty((n_samples, *n_bins))
    posterior[:] = np.nan

    # decode each sample / bin separately
    for tt in range(n_samples):
        obs = X[tt]
        if obs.sum() > 0:
            posterior[tt] = (tile_obs(obs, *n_bins) * lfx).sum(axis=0) + eterm

    # normalize posterior:
    posterior = np.exp(
        posterior
        - logsumexp(posterior, axis=tuple(np.arange(1, n_dims + 1)), keepdims=True)
    )

    if n_dims > 1:
        expected = []
        for dd in range(1, n_dims + 1):
            axes = tuple(set(np.arange(1, n_dims + 1)) - set([dd]))
            expected.append(
                (bin_centers[dd - 1] * posterior.sum(axis=axes)).sum(axis=1)
            )
        expected_pth = np.vstack(expected).T
    else:
        expected_pth = (bin_centers * posterior).sum(axis=1)

    return posterior, expected_pth