How to use the nltools.data.design_matrix.Design_Matrix function in nltools

To help you get started, we’ve selected a few nltools examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cosanlab / nltools / nltools / data / design_matrix.py View on Github external
def replace_data(self, data, column_names=None):
        """Convenient method to replace all data in Design_Matrix with new data while keeping attributes and polynomial columns untouched.

        Args:
            columns_names (list): list of columns names for new data

        """

        if isinstance(data, np.ndarray) or isinstance(data, pd.DataFrame) or isinstance(data, dict):
            if data.shape[0] == self.shape[0]:
                out = Design_Matrix(data, columns=column_names)
                polys = self[self.polys]
                out = pd.concat([out, polys], axis=1)
                out = self._inherit_attributes(out)
                return out
            else:
                raise ValueError("New data cannot change the number of rows")
        else:
            raise TypeError("New data must be numpy array, pandas DataFrame or python dictionary type")
github cosanlab / nltools / nltools / data / design_matrix.py View on Github external
def upsample(self, target, **kwargs):
        """Upsample columns of design matrix. Relies on
            nltools.stats.upsample, but ensures that returned object is a
            design matrix.

        Args:
            target(float): desired frequence in hz
            kwargs: additional inputs to nltools.stats.downsample

        """
        if target < self.sampling_freq:
            raise ValueError("Target must be shorter than current sampling rate")

        df = Design_Matrix(upsample(self, sampling_freq=self.sampling_freq, target=target, target_type='hz', **kwargs))

        # convert df to a design matrix
        newMat = self._inherit_attributes(df)
        newMat.sampling_freq = target
        return newMat
github cosanlab / nltools / nltools / data / design_matrix.py View on Github external
norm_order = np.linspace(-1, 1, self.shape[0])

        if 'poly_'+str(order) in self.polys:
            print("Design Matrix already has {}th order polynomial...skipping".format(order))
            return self

        if include_lower:
            for i in range(order+1):
                if 'poly_'+str(i) in self.polys:
                    print("Design Matrix already has {}th order polynomial...skipping".format(i))
                else:
                    polyDict['poly_' + str(i)] = legendre(i)(norm_order)
        else:
            polyDict['poly_' + str(order)] = legendre(order)(norm_order)

        toAdd = Design_Matrix(polyDict, sampling_freq=self.sampling_freq)
        out = self.append(toAdd, axis=1)
        if out.polys:
            new_polys = out.polys + list(polyDict.keys())
            out.polys = new_polys
        else:
            out.polys = list(polyDict.keys())
        return out
github cosanlab / nltools / nltools / data / design_matrix.py View on Github external
def __init__(self, *args, **kwargs):

        sampling_freq = kwargs.pop('sampling_freq', None)
        convolved = kwargs.pop('convolved', [])
        polys = kwargs.pop('polys', [])
        self.sampling_freq = sampling_freq
        self.convolved = convolved
        self.polys = polys
        self.multi = False

        super(Design_Matrix, self).__init__(*args, **kwargs)
        # Ensure that column names are string types to all methods work
        if not self.empty:
            self.columns = [str(elem) for elem in self.columns]
github cosanlab / nltools / nltools / data / design_matrix.py View on Github external
def _constructor_expanddim(self):
        return Design_Matrix
github cosanlab / nltools / nltools / data / adjacency.py View on Github external
Args:
                X: Design matrix can be an Adjacency or Design_Matrix instance
                method: type of regression (default: ols)

            Returns:
                stats: (dict) dictionary of stats outputs.
        '''

        stats = {}
        if isinstance(X, Adjacency):
            if X.square_shape()[0] != self.square_shape()[0]:
                raise ValueError('Adjacency instances must be the same size.')
            b, t, p, _, res = regression(X.data.T, self.data, mode=mode, **kwargs)
            stats['beta'], stats['t'], stats['p'], stats['residual'] = (b, t, p, res)
        elif isinstance(X, Design_Matrix):
            if X.shape[0] != len(self):
                raise ValueError('Design matrix must have same number of observations as Adjacency')
            b, t, p, df, res = regression(X, self.data, mode=mode, **kwargs)
            mode = 'ols'
            stats['beta'], stats['t'], stats['p'] = [x for x in self[:3]]
            stats['beta'].data, stats['t'].data, stats['p'].data = b.squeeze(), t.squeeze(), p.squeeze()
            stats['residual'] = self.copy()
            stats['residual'].data = res
            stats['df'] = df
        else:
            raise ValueError('X must be a Design_Matrix or Adjacency Instance.')

        return stats
github cosanlab / nltools / nltools / data / design_matrix.py View on Github external
def downsample(self, target, **kwargs):
        """Downsample columns of design matrix. Relies on
            nltools.stats.downsample, but ensures that returned object is a
            design matrix.

        Args:
            target(float): desired frequency in hz
            kwargs: additional inputs to nltools.stats.downsample

        """
        if target > self.sampling_freq:
            raise ValueError("Target must be longer than current sampling rate")

        df = Design_Matrix(downsample(self, sampling_freq=self.sampling_freq, target=target, target_type='hz', **kwargs))

        # convert df to a design matrix
        newMat = self._inherit_attributes(df)
        newMat.sampling_freq = target
        return newMat