Пример #1
0
class TestThreading(Method):
    argsList = MethodArgList()
    argsList.append('timeToSleep', 2, int, 'seconds to sleep')
    argsList.append('plot', False, bool, 'plot or not')
    argsList.append('type', ['menu1', 'menu2', 'menu3'], list, 'menu test')
    ''' Constuctor '''
    def __init__(self, timeToSleep, plot, type, **kwargs):
        ' Raise error if parameters are not in the correct type '
        #Method.__init__(self)
        super(TestThreading, self).__init__(plot, **kwargs)

        self.timeToSleep = timeToSleep
        self.type = type

    def compute(self, signals):
        try:
            if not (isinstance(self.timeToSleep, int)):
                raise TypeError("Requires time to be an integer")
        except TypeError, err_msg:
            self.errorRaised = True
            return "Error: " + str(err_msg)

        ' Raise error if parameters do not respect input rules '
        try:
            if self.timeToSleep <= 0:
                raise ValueError(
                    "Requires time to be a positive integer different from 0")
        except ValueError, err_msg:
            self.errorRaised = True
            return "Error: " + str(err_msg)
Пример #2
0
class GrangerCausality(Method):
    """
    It computes a Granger causality test between two univariate signals x and y (in pandas DataFrame format). It computes
    unidirectionnal causality test with a bivariate autoregressive model and test if the unrestricted model is statistically
    significant compared to the restricted one. An F-test is computed and then the interpretation is up to the user.

    **Reference :**

    * Anil K. Seth. A MATLAB toolbox for Granger causal connectivity analysis. Journal of Neuroscience Methods, 186(2) :262-273, February 2010.

    :param max_lag:
        The number of maximum lag (in samples) with which the autoregressive model will be computed.
        It ranges in [1;length(x)]. Default : 1.
    :type max_lag: int

    :param criterion: A string that contains the name of the selected criterion to estimate optimal number of lags value.
        Two choices are possible :
            1.'bic' (Bayesian Information Criterion);
            2.'aic' (Akaike Information Criterion)
        Default : 'bic'
    :type criterion: str

    :param plot:
        if True the plot of correlation function is returned. Default: False
    :type plot: bool
    """
    argsList = MethodArgList()
    argsList.append(
        'max_lag', 1, int,
        'The number of maximum lag (in samples) with which the autoregressive model will be computed'
    )
    argsList.append('criterion', ['bic', 'aic'], list,
                    'criterion to estimate optimal number of lags value')
    argsList.append('plot', False, bool, ' plot of correlation function ')
    ''' Constructor '''
    def __init__(self, max_lag=1, criterion='bic', plot=False, **kwargs):
        super(GrangerCausality, self).__init__(plot, **kwargs)
        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(plot, bool)):
                raise TypeError("Requires plot to be a bool")
            if not (isinstance(criterion, str)):
                raise TypeError("Requires criterion to be a str")
            if not (isinstance(max_lag, int)):
                raise TypeError("Requires max_lag to be an int")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '

        try:
            if max_lag <= 0:
                raise ValueError(
                    "Requires max_lag to be a strictly positive scalar")
            if criterion != 'bic' and criterion != 'aic':
                raise ValueError("Requires criterion to be 'bic' or 'aic'")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #3
0
class PhaseSynchro_Strobo(Method):
    """
    It computes n:m synchronization index lambda_nm by using a stroboscopic approach between two univariate signals x and y
    (in pandas DataFrame format).
   
    **Reference :**
    M. Rosenblum, A. Pikovsky, J. Kurths, C. Schafer and P. A. Tass. Phase synchronizatio:from theory to practice. In Handbook of Biological Physics,
    Elsiever Science, Series Editor A.J. Hoff, Vol. , Neuro-Informatics, Editors: F. Moss and S. Gielen, Chapter 9.
    
    :param n:
        it is the integer for the order of synchronization 
    :type n: int 
    
    :param m:
        it is the integer for the order of synchronization 
    :type m: int

    :param nbins:
        it is the number of bins to be used to build phase distribution
    :type nbins: int

    """
    argsList = MethodArgList()
    argsList.append('n', 1, int,
                    'it is the integer for the order of synchronization')
    argsList.append('m', 1, int,
                    'it is the integer for the order of synchronization ')
    argsList.append(
        'nbins', 10, int,
        'it is the number of bins to be used to build phase distribution')
    ''' Constructor '''
    def __init__(self, n=1, m=1, nbins=10, **kwargs):
        super(PhaseSynchro_Strobo, self).__init__(plot=False, **kwargs)

        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(n, int)):
                raise TypeError("Requires n to be a np.array of integers")
            if not (isinstance(m, int)):
                raise TypeError("Requires m to be a np.array of integers")
            if not (isinstance(nbins, int)):
                raise TypeError("Requires nbins to be an integer")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if n <= 0:
                raise ValueError("Requires n to have a size greater than 0")
            if m <= 0:
                raise ValueError("Requires n to have a size greater than 0")
            if nbins <= 0:
                raise ValueError("Requires nbins to be a positive scalar")

        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #4
0
    def generatePy(self):
        name = self.ui.nameTextEdit.text()
        author = self.ui.authorTextEdit.text()
        desc = self.ui.descriptionTextEdit.toPlainText()

        type = self.ui.variatComboBox.currentText()
        categ = self.ui.categoryComboBox.currentText()
        sigNumber = self.ui.inputSignalNumberComboBox.currentText()

        rowCount = self.model.rowCount()
        colCount = self.model.columnCount()
        argList = MethodArgList()
        for i in range(0, rowCount):
            argList.append(self.model.item(i, 0).text()
                           , self.model.item(i, 2).text()
                           , self.model.item(i, 1).text()
                           , self.model.item(i, 3).text())

        self.generatePython(name, author, desc, type, categ, sigNumber, argList)
Пример #5
0
class Omega_Complexity(Method):
    """
    It computes Omega complexity among many monovariate signals (organized as a list of pandas DataFrame).
    It is a measure based on spatial principal component analysis (SPCA) carried out on the covariance matrix of the DataFrame. It ranges in [0,N], where 1 stands for maximum synchrony, N minimum synchrony.
    
    **Reference :**
    
    * Wackermann, J. Beyond mapping: estimating complexityof multichannel EEG recordings. Acta Neurobiol. Exp., 1996, 56:197-208.
 
    """
    argsList = MethodArgList()
 
    ''' Constructor '''
    def __init__(self, plot = False, **kwargs):
        super(Omega_Complexity, self).__init__(plot, **kwargs)
        pass

    def plot_result(self):
        pass
    
    def compute(self, signals):
        """
        It computes the Omega complexity for multiple monovariate signals (organized as a list).
        If input signals are multivariates, only the first column of the signal is considered
        
        :param signals:
            list of signals, one per person. 
        :type signals: list[pd.DataFrame]
        
        :returns: dict
            -- omega
        
        """
        
        ' Raise error if parameters are not in the correct type '
        try :
            for i in range(len(signals)) :
                if not(isinstance(signals[i], pd.DataFrame)): raise TypeError("Requires signal " + str(i+1) + " to be a pd.DataFrame.")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return
        
        ' Raise error if DataFrames have not the same size or same indexes '
        try :
            for i in range(0,len(signals)):
                if len(signals[0]) != len(signals[i]) : raise ValueError("All the signals must have the same size. Signal " + str(i+1) + " does not have the same size as first signal.")
                if signals[0].index.tolist() != signals[i].index.tolist() : raise ValueError("All the signals must have the same time indexes. Signal " + str(i+1) + " does not have the same time index as first signal.")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #6
0
class PhaseSynchro_Fourier(Method):
    """
    It computes n:m synchronization index gamma2_nm as the intensity of the first Fourier mode of the cyclic relative phase of two univariate signals x and y
    (in pandas DataFrame format). Gamma2_nm ranges in [0,1] where 0 means no synchronization at all and 1 means perfect synchronization.
   
    **Reference :**
    M. Rosenblum, A. Pikovsky, J. Kurths, C. Schafer and P. A. Tass. Phase synchronizatio:from theory to practice. In Handbook of Biological Physics,
    Elsiever Science, Series Editor A.J. Hoff, Vol. , Neuro-Informatics, Editors: F. Moss and S. Gielen, Chapter 9.
    
    :param n:
        it is the integer for the order of synchronization 
    :type n: int 
    
    :param m:
        it is the integer for the order of synchronization 
    :type m: int
    

    """
    argsList = MethodArgList()
    argsList.append('n', 1, int,
                    'it is the integer for the order of synchronization')
    argsList.append('m', 1, int,
                    'it is the integer for the order of synchronization ')
    ''' Constructor '''
    def __init__(self, n=1, m=1, **kwargs):
        super(PhaseSynchro_Fourier, self).__init__(plot=False, **kwargs)
        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(n, int)):
                raise TypeError("Requires n to be an integer")
            if not (isinstance(m, int)):
                raise TypeError("Requires m to be an integer")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if n <= 0:
                raise ValueError("Requires n to have a size greater than 0")
            if m <= 0:
                raise ValueError("Requires n to have a size greater than 0")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #7
0
class S_Estimator(Method):
    """
    S_Estimator computes the S-Estimator, Genuine and Random Synchronization index among multiple monovariate signals (organized as a list of pandas DataFrame). 
    
    **Reference :**
    
    * Cui, D. and al., Estimation of genuine and random synchronization in multivariate neural series. Neural Networks 23 (2010) 698-704.
    * Andrzejak, R. and al., Bivariate surrogate techniques: Necessity, strengths, and caveats. Physical Review E 68, 066202 (2003). 
    * Schreiber, T. and al., Surrogate time series. Physica D 142 (2000) 346-382.
    
    :param surr_nb_iter:
        Number of surrogate iterations. Default : 100 
    :type surr_nb_iter: int
    
    :param plot:
        if True the plot of surrogates signals is returned. Default: False
    :type plot: bool
    """
    argsList = MethodArgList()
    argsList.append('surr_nb_iter', 100, int,
                    'Number of surrogate iterations.')
    argsList.append('plot', False, bool, 'plot of surrogates signals is returned')

    ''' Constructor '''
    def __init__(self, surr_nb_iter = 100, plot = False, **kwargs):
        super(S_Estimator, self).__init__(plot, **kwargs)
        #In the constructor we can check that params have corrects values and initialize stuff
        
        ' Raise error if parameters are not in the correct type '
        try :
            if not(isinstance(surr_nb_iter, int)) : raise TypeError("Requires surr_nb_iter to be an integer")
            if not(isinstance(plot, bool))        : raise TypeError("Requires plot to be a boolean")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return
        
        ' Raise error if parameters do not respect input rules '
        try : 
            if surr_nb_iter <= 0 : raise ValueError("Requires surr_nb_iter to be a strictly positive scalar")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #8
0
class NonlinearCorr(Method):
    """
    It computes the nonparametric nonlinear regression coefficient h2 describing the dependency between two univariate signals x and y (in pandas DataFrame format) in the most general way.
    It is equal to 0 when the two signals are independent, 1 when they are perfectly dependent.
    
    **Reference :**
    
    * F.Lopes da Silva, P. J.P., and B.P. Interdependence of eeg signals: linear vs. nonlinear associations and the signifcance of time delays and phase shifts. BrainTopography,2:9-18, 1989.
    
    :param nbins:
        number of bins in which the time series is divided into. 
    :type nbins: int
    """
    argsList = MethodArgList()
    argsList.append('nbins', 100, int,
                    'number of bins in which the time series is divided into')
    ''' Constuctor '''
    def __init__(self, nbins, **kwargs):
        ' Raise error if parameters are not in the correct type '
        super(NonlinearCorr, self).__init__(plot=False, **kwargs)

        try:
            if not (isinstance(nbins, int)):
                raise TypeError("Requires tau_max to be an integer")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if nbins <= 0:
                raise ValueError(
                    "Requires nbins to be a positive integer different from 0")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #9
0
class GSI(Method):
    """
    It computes the generalised synchronization index (GSI) between two uni/multi-variate signals x and y(in DataFrame format).
    GSI ranges in [0,1] where 0 means no synchronization and 1 perfect generalized synchronization.
    
    :param m:
        embedding dimension
    :type m: int
    
    :param t:
        embedding delay
    :type t: int
    
    :param rr:
        recurrence rate
    :type t: float
    
    """
    argsList = MethodArgList()
    argsList.append('m', 1, int, 'embedding dimension')
    argsList.append('t', 1, int, 'embedding delay')
    argsList.append('rr', 0.1, float, 'recurrence rate')

    ''' Constructor '''
    def __init__(self, m, t, rr, **kwargs):
        ' Raise error if parameters are not in the correct type '
        super(GSI, self).__init__(plot=False, **kwargs)
        #In the constructor we can check that params have corrects values and initialize stuff
        ' Raise error if parameters are not in the correct type '
        if not(isinstance(m, int))   : raise TypeError("Requires m to be an integer")
        if not(isinstance(t, int))   : raise TypeError("Requires t to be a integer")
        if not(isinstance(rr, float)): raise TypeError("Requires rr to be a float")
        
        ' Raise error if parameters do not respect input rules '
        if m <= 0 : raise ValueError("Requires m to be positive and greater than 0")
        if t <= 0 : raise ValueError("Requires t to be positive and  greater from 0")
        if rr <= 0: raise ValueError("Requires eps to be positive")

        self._m = m
        self._t = t 
        self._rr = rr
        
        return

    def compute(self, signals):
        """
        It computes GSI
         
        :param signals:
            array of two input signals as pd.DataFrame
        :type signals: list
        
        :returns: dict
            -- gsi 
        """
        x = signals[0]
        y = signals[1]


        ' Raise error if parameters are not in the correct type '
        if not(isinstance(x, pd.DataFrame)): raise TypeError("Requires x to be a pd.DataFrame")
        if not(isinstance(y, pd.DataFrame)): raise TypeError("Requires y to be a pd.DataFrame")

        standardization = True
        plot = False
        
        jrp = JointRecurrencePlot.JointRecurrencePlot(x, y, self._m, self._t, self._rr, 'rr', standardization, plot)
        
        f_jrp = (1 - jrp['jrp']).flatten()
        
        jrr = np.mean(f_jrp)
        
        GSI_no_norm = jrr / self._rr
                
        GSI = (GSI_no_norm - self._rr) / (1 - self._rr)
        
        if GSI > 1:
            GSI = 1
           
        result = dict()
        result['GSI'] = GSI

        return result


    @staticmethod
    def getArguments():
        return GSI.argsList.getMethodArgs()


    @staticmethod
    def getArgumentsAsDictionary():
        return GSI.argsList.getArgumentsAsDictionary()
Пример #10
0
class CCA(Method):
    """
   extract the highest correlations possible between projections of the features of the two datasets.
   datasets must contain the same number of row (individual or sample)
   But can contain different number of feature (i.e different number of rows)
   
   returns the weight of projections
   and correlations that comes with those weights
   """
    argsList = MethodArgList()
    argsList.append('xData_filename', '', file, 'First data set in cvs format')
    argsList.append('yData_filename', '', file,
                    'Second data set in cvs format')
    argsList.append('nbr_correlations', 0, int,
                    'number of maximised correlations wanted')
    argsList.append('standerdized', False, bool,
                    'are the two datasets centered and reduced')

    def __init__(self,
                 plot=False,
                 nbr_correlations=0,
                 standerdized=False,
                 xData=None,
                 yData=None,
                 xData_filename=None,
                 yData_filename=None,
                 **kwargs):
        ' Init '
        super(CCA, self).__init__(plot, **kwargs)
        if xData is None:
            if not (xData_filename and isinstance(xData_filename, file)) \
                    or len(xData_filename.name) == 0:
                raise TypeError("Requires xData_filename to be a file")

        if yData is None:
            if not (yData_filename and isinstance(yData_filename, file)) \
                    or len(yData_filename.name) == 0:
                raise TypeError("Requires yData_filename to be a file")

        if not (isinstance(nbr_correlations, int)):
            raise TypeError("Requires m to be an integer")
        if not (isinstance(standerdized, bool)):
            raise TypeError("Requires center to be a boolean")
        #other rule for parameters
        if nbr_correlations < 0:
            raise ValueError("Requires m to be positive or greater than 0")

        if isinstance(xData_filename, file):
            xData = pd.DataFrame.from_csv(xData_filename)

        if isinstance(yData_filename, file):
            yData = pd.DataFrame.from_csv(yData_filename)

        if not (isinstance(xData, pd.DataFrame)):
            raise TypeError("Requires xData to be a panda dataframe")
        if not (isinstance(yData, pd.DataFrame)):
            raise TypeError("Requires yData to be a panda dataframe")

        self._xData = xData
        self._yData = yData
        self._nbr_correlations = nbr_correlations
        self._standerdized = standerdized
        self.lx = None
        self.ly = None

        return

    def vector_root(self, V):
        l = V.size
        U = np.array(V, float)
        for i in range(0, l):
            U[i] = sqrt(U[i])
        return U

    def inv_vector_root(self, V):
        l = V.size
        U = np.array(V, float)
        for i in range(0, l):
            if (V[i] > 0):
                U[i] = 1 / sqrt(U[i])
            else:
                V[i] = 0
        return U

    def cov(self, A, B):
        l, c = A.shape
        aux = 1.0 / (l - 1)
        sigma = aux * np.dot(A.T, B)
        return sigma

    def SVD_CCA(self, S_X, S_Y, S_XY, m):
        D, v_x = eig(S_X)
        D = self.inv_vector_root(D)
        D = diag(D)
        CX = np.dot(np.dot(v_x, D), inv(v_x))
        D, v_y = eig(S_Y)
        D = self.inv_vector_root(D)
        D = diag(D)
        CY = np.dot(np.dot(v_y, D), inv(v_y))
        omega = np.dot(np.dot(CX, S_XY), CY)
        U, D, T = svd(omega, full_matrices=0)
        A = np.dot(CX, U)
        A = A[:, :m]
        B = np.dot(CY, T.T)
        B = B[:, :m]
        D = D[0:m]
        D = self.vector_root(D)
        return D, B, A

    def compute(self, signals):

        x = self._xData
        y = self._yData

        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(x, pd.DataFrame)):
                raise TypeError("Requires x to be a pd.DataFrame")
            if not (isinstance(y, pd.DataFrame)):
                raise TypeError("Requires y to be a pd.DataFrame")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return
        if not self._standerdized:
            x = Standardize.Standardize(x)
            y = Standardize.Standardize(y)
        x = x.values
        y = y.values
        if self._nbr_correlations == 0:
            self.lx = x.shape[1]
            self.ly = y.shape[1]
            self._nbr_correlations = min(self.lx, self.ly)
        cov_x = self.cov(x, x)
        cov_y = self.cov(y, y)
        cov_xy = self.cov(x, y)
        D, A, B = self.SVD_CCA(cov_x, cov_y, cov_xy, self._nbr_correlations)

        res = {}
        res['corr'] = D
        res['yWeights'] = A
        res['xWeights'] = B

        return res
Пример #11
0
class BooleanTurnsActivity(Method):
    """
    It computes data turns statistics between two boolean univariate signals (in pandas DataFrame format) x and y :
    x signal activity duration, y signal activity duration, pause duration, overlap duration,
    x signal pause duration, y signal pause duration, pause duration between x and y activity,
    synchrony ratios between x and y (defined by max_latency).
    
    :param max_latency:
        the maximal delay (in second) between the two signals activity to define synchrony 
    :type max_latency: float
    
    :param min_pause_duration:
        minimal time (in second) for defining a pause 
    :type min_pause_duration: float
    
    :param ele_per_sec:
        number of elements in one second. Default: 1
    :type ele_per_sec: int
    
    :param duration:
        total activity duration (in second). If -1, duration = len(x)*ele_per_sec. Default : -1
    :type duration: int
    """
    argsList = MethodArgList()
    argsList.append(
        'max_latency', 1, float,
        'the maximal delay (in second) between the two signals activity to define synchrony'
    )
    argsList.append('min_pause_duration', 1, float,
                    'minimal time (in second) for defining a pause ')
    argsList.append('ele_per_sec', 1, int, 'number of elements in one second')
    argsList.append('duration', 1, int, 'total activity duration (in second)')
    ''' Constructor '''
    def __init__(self,
                 max_latency,
                 min_pause_duration,
                 ele_per_sec=1,
                 duration=-1,
                 **kwargs):
        super(BooleanTurnsActivity, self).__init__(plot=False, **kwargs)
        try:
            if not (isinstance(max_latency, float)):
                raise TypeError("Requires max_latency to be an float")
            if not (isinstance(min_pause_duration, float)):
                raise TypeError("Requires min_pause_duration to be an integer")
            if not (isinstance(ele_per_sec, int)):
                raise TypeError("Requires ele_per_sec to be an integer")
            if not (isinstance(duration, int)):
                raise TypeError("Requires duration to be an integer")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        try:
            if max_latency < 0:
                raise ValueError(
                    "Requires max_latency to be a positive scalar")
            if min_pause_duration < 0:
                raise ValueError(
                    "Requires min_pause_duration to be a positive scalar")
            if ele_per_sec <= 0:
                raise ValueError(
                    "Requires ele_per_sec to be a strictly positive scalar")
            if duration != -1 and duration <= 0:
                raise ValueError(
                    "Requires duration to be a strictly positive scalar (or -1)"
                )
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #12
0
class oneclassSVMimitation(Method):
    """
    It compute the recurrence matrix between two videos in order to detect imitation. The data used is STIP (Space-Time Interest Points) extracted
    from each video using Ivan LAPTEV stip.exe.
    This code is inspired by "Automatic measure of imitation during social interaction: A behavioraland hyperscanning-EEG benchmark"
    credits to: Emilie Delaherche, Guillaume Dumas, Jacqueline Nadel, Mohamed Chetouani

    example:
        -Walk-simple.avi===>apply stip.exe=====>walk-simple.csv ====> put csv file generated in video1_STIP(SyncPy\src\samples\video1_STIP)
        -Walk-complex.avi===>apply stip.exe=====>walk-complex.csv ====> put csv file generated in video2_STIP(SyncPy\src\samples\video2_STIP)
        -Now you are set (see example provided in example folder in SyncPy\examples\oneclassSVMimitation)

        -Instructions on how to extract STIP yourself are in README file in Syncpy/src/samples/ExtractSTIP/
        -The link to Ivan LAPTEV: https://www.di.ens.fr/~laptev/interestpoints.html for further details.

    :param vid1file
        the  path the first video
    :type vid1file: file

    :param vid2file
        the path to the second video
    :type vid2file: file

    :param K
        number of words in the codebook or the codewords or visual vocabulary or K means number of clusters
    :type K: int


    :param threshold
        threshold on oneClassSVM scores
    :type threshold: float

"""

    argsList = MethodArgList()
    argsList.append('vid1file', '', file, 'the  path the first video ')
    argsList.append('vid2file', '', file, 'the path to the second video ')
    argsList.append(
        'K', 100, int,
        ' number of words in the codebook or the codewords or visual vocabulary or K means number of clusters'
    )
    argsList.append('threshold', 0.1, float,
                    'threshold on oneClassSVM scores ')
    argsList.append('plot', False, bool,
                    'if True the plot of Recurrence Matrix')

    def __init__(self,
                 vid1file,
                 vid2file,
                 K,
                 threshold=0.1,
                 plot=False,
                 **kwargs):
        super(oneclassSVMimitation, self).__init__(plot, **kwargs)
        """
        -init:
            vid1file: the  path the first video
            vid2file: the  path the second video
            K: number of words in the codebook or the codewords or visual vocabulary or K means number of clusters
            windowsize: number of frames for each training vector  example of 2 frame : vect[1,2]--vect[3,4]--vect[5,6]
            threshold: Rij=heaviside(threshold-Sab) where Rij is the recurrence matrix
        """

        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(vid1file, file)):
                raise TypeError("Requires vid1file to be an file")
            if not (isinstance(vid2file, file)):
                raise TypeError("Requires vid2file to be an file")
            if not (isinstance(K, int)):
                raise TypeError("Requires K to be an integer")
            if not (isinstance(threshold, float)):
                raise TypeError("Requires threshold to be a float")
            if not (isinstance(plot, bool)):
                raise TypeError("Requires plot to be a boolean")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        self.vid1file = str(vid1file.name)
        self.vid2file = str(vid2file.name)
        self.K = K
        self.threshold = threshold
Пример #13
0
class EventSync(Method):
    """
   It computes synchronicity (Q) and time delay patterns (q) between two univariate signals x and y
   (in pandas DataFrame format) in which events can be identified.  
   
   **Reference :**
   
   * R.Quian Quiroga; T.Kreuz and P.Grassberger. "A simple and fast method to measure synchronicity and time delay patterns." (Phys.Rev. E; 66; 041904 (2002))
   
   :param atype:
       it can assumes the following values: 'tot', 'tsl', 'asl' \n
         1. 'tot': synchronicity (Q) and time delay pattern(q) are computed over all the time signals
         2. 'tsl': time resolved variants of Q and q\n
         3. 'asl': averaged time resolved variants of Q and q over a window whose size is specified by the window parameter
       Default: 'tot
   :type atype: str
   
   :param tau:
      it is a binary value [0,1] indicating which type of algorithm is used to estimates the delay. \n
         1. 0 : a prefixed tau with value specified by lag_tau will be used. It should be smaller than half the minimum interevent distance
         2. 1 : an atuomatically estimated local tau for each pair of events in the series will be used. The local tau for a generic pair of events i and j is computed as the half of the minimum value in the following set
      [tau_x(i+1)- tau_x(i); tau_x(i)-tau_x(i-1); tau_y(j+i)-tau_y(j), tau_y(j)-tau_y(j-1)]
      Default: 1
   :type tau: int
   
   :param lag_tau:
      it is the (positive) number of samples will be used as delay when tau is set to 0
   :type lag_tau: int
   
   :param window:
      it is the size of the window (in samples) used to compute Q and q when type is 'asl'.
   :type window: int
   
   :param plot:
      if True the plot of Q and q is returned when atype is set to 'tsl' or 'asl'. Default: False
   :type plot: bool 
   """
    argsList = MethodArgList()
    argsList.append('atype', ['tot', 'tsl', 'asl'], list, 'type')
    argsList.append('tau', 1, int,
                    'which type of algorithm is used to estimates the delay')
    argsList.append(
        'lag_tau', 1, int,
        'the (positive) number of samples will be used as delay when tau is set to 0'
    )
    argsList.append(
        'window', 1, int,
        'the size of the window (in samples) used to compute Q and q when type is asl'
    )
    argsList.append(
        'plot', False, bool,
        'True the plot of Q and q is returned when atype is set to tsl or asl')

    def __init__(self,
                 atype='tot',
                 tau=0,
                 lag_tau=0,
                 window=1,
                 plot=False,
                 **kwargs):
        super(EventSync, self).__init__(plot, **kwargs)
        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(atype, str)):
                raise TypeError("Requires type to be a string")
            if not (isinstance(tau, int)):
                raise TypeError("Requires tau to be an integer")
            if not (isinstance(lag_tau, int)):
                raise TypeError("Requires lag_tau to be an integer")
            if not (isinstance(window, int)):
                raise TypeError("Requires window to be an integer")
            if not (isinstance(plot, bool)):
                raise TypeError("Requires plot to be a boolean")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if atype != 'tot' and atype != 'tsl' and atype != 'asl':
                raise ValueError(
                    "Requires type to be have these values : {'tot', 'tsl', 'asl'}"
                )
            if tau != 0 and tau != 1:
                raise ValueError("Requires tau to be to be 1 or 2")
            if lag_tau < 0:
                raise ValueError(
                    "Requires lag_tau to be a positive scalar inferior to window length"
                )
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #14
0
class WindowCrossCorrelation(Method):
    """
    It computes the window cross correlation between two univariate signals (in pandas DataFrame format) x and y 
    
    :param tau_max:
        the maximum lag (in samples) at which correlation should be computed. It is in the range [0; (length(x)+length(y)-1)/2] 
    :type tau_max: int
    
    :param window:
        length (in samples) of the windowed signals 
    :type window: int
    
    :param win_inc:
        amount of time (in samples) elapsed between two windows 
    :type win_inc: int
    
    :param tau_inc:
        amount of time (in samples) elapsed between two cross-correlation 
    :type tau_inc: int
    
    :param plot:
        if True the plot of correlation function is returned. Default: False
    :type plot: bool
    
    :param ele_per_sec:
       number of element in one second
    :type ele_per_sec: int  
    """
    argsList = MethodArgList()
    argsList.append(
        'tau_max', 0, int,
        'the maximum lag (in samples) at which correlation should be computed. It is in the range [0; (length(x)+length(y)-1)/2]'
    )
    argsList.append('window', 0, int,
                    'length (in samples) of the windowed signals')
    argsList.append('win_inc', 1, int,
                    'amount of time (in samples) elapsed between two windows')
    argsList.append(
        'tau_inc', 1, int,
        'amount of time (in samples) elapsed between two cross-correlation')
    argsList.append('plot', False, bool,
                    'if True the plot of correlation function is returned')
    argsList.append('ele_per_sec', 1, bool, 'number of element in one second')
    ''' Constructor '''
    def __init__(self,
                 tau_max=0,
                 window=0,
                 win_inc=1,
                 tau_inc=1,
                 plot=False,
                 ele_per_sec=1,
                 **kwargs):
        super(WindowCrossCorrelation, self).__init__(plot, **kwargs)

        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(tau_max, int)):
                raise TypeError("Requires tau_max to be an integer")
            if not (isinstance(window, int)):
                raise TypeError("Requires window to be an integer")
            if not (isinstance(win_inc, int)):
                raise TypeError("Requires win_inc to be an integer")
            if not (isinstance(tau_inc, int)):
                raise TypeError("Requires tau_inc to be an integer")
            if not (isinstance(plot, bool)):
                raise TypeError("Requires plot to be a boolean")
            if not (isinstance(ele_per_sec, int)):
                raise TypeError("Requires ele_per_sec to be an integer")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if tau_max < 0:
                raise ValueError("Requires tau_max to be a positive scalar")
            if window < 0:
                raise ValueError("Requires window to be a positive scalar")
            if win_inc < 0 or win_inc >= window:
                raise ValueError(
                    "Requires win_inc to be a positive scalar inferior to window length"
                )
            if tau_inc < 0 or tau_inc > tau_max:
                raise ValueError(
                    "Requires tau_inc to be a positive scalar inferior to tau_max length"
                )
            if ele_per_sec <= 0:
                raise ValueError(
                    "Requires ele_per_sec to be a strictly positive scalar")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #15
0
class PeakPicking(Method):
    """
    It computes peak picking algorithm with window cross correlation results (see WindowCrossCorrelation)
        
    :param corr_matrix:
        matrix of cross correlation computed by WindowCrossCorrelation module
        (windowed cross correlation DataFrame with (2 * tau_max + 1)/tau_inc rows and (length(x) - window - win_inc)/ win_inc colums) 
    :type corr_matrix: pd.DataFrame
    
    :param tau_max:
        the maximum lag (in samples) at which correlation should be computed. It is in the range [0, (length(x)+length(y)-1)/2]  
    :type tau_max: int
    
    :param tau_inc:
        amount of time (in samples) elapsed between two cross-correlation 
    :type tau_inc: int
    
    :param threshold:
        minimal correlation magnitude acceptable for a peak. It is in the range [-1;1]
    :type threshold: float
    
    :param lookahead:
        distance to look ahead from a peak candidate to determine if it is the actual peak. Default: 200
        (sample / period) / f where 4 >= f >= 1.25 might be a good value
    :type lookahead: int
    
    :param delta:
        it specifies a minimum difference between a peak and the following points, before a peak may be considered a peak.
        Useful to hinder the function from picking up false peaks towards to end of the signal.
        To work well delta should be set to delta >= RMSnoise * 5. Default: 0
    :type delta: int
    
    :param ele_per_sec:
       number of elements in one second
    :type ele_per_sec: int
    
    :param plot:
        if True the plot of peakpicking function is returned. Default: False
    :type plot: bool
    
    :param plot_on_mat:
        if True the plot of peakpicking + correlation matrix function is returned. Default: False
    :type plot_on_mat: bool
    
    :param sorted_peak:
        if True the peaks found will be organized by type of Lag and Magnitude (positive or negative). Default: False
    :type sorted_peak: bool
    """
    argsList = MethodArgList()
    argsList.append(
        'corr_matrix_filename', '', file,
        'Data json file containing matrix of cross correlation computed by WindowCrossCorrelation module (windowed cross correlation DataFrame with (2 * tau_max + 1)/tau_inc rows and (length(x) - window - win_inc)/ win_inc colums)'
    )
    argsList.append(
        'tau_max', 10, int,
        'The maximum lag (in samples) at which correlation should be computed. It is in the range [0; (length(x)+length(y)-1)/2]'
    )
    argsList.append(
        'tau_inc', 1, int,
        'Amount of time (in samples) elapsed between two cross-correlation ')

    argsList.append(
        'threshold', 0.5, float,
        'minimal correlation magnitude acceptable for a peak. It is in the range [-1;1]'
    )
    argsList.append(
        'lookahead', 2, int,
        'Distance to look ahead from a peak candidate to determine if it is the actual peak. Default: 200 (sample / period) / f where 4 >= f >= 1.25 might be a good value'
    )
    argsList.append(
        'delta', 0, int,
        'Minimum difference between a peak and the following points, before a peak may be considered a peak.'
    )
    argsList.append('ele_per_sec', 2, int, 'Number of elements in one second')

    argsList.append('plot', False, bool,
                    'if True the plot of correlation function is returned')
    argsList.append(
        'plot_on_mat', False, bool,
        'Plot of peakpicking + correlation matrix function is returned')
    argsList.append(
        'sorted_peak', False, bool,
        'Peaks found will be organized by type of Lag and Magnitude (positive or negative'
    )
    ''' Constructor '''
    def __init__(self,
                 corr_matrix=None,
                 tau_max=0,
                 tau_inc=0,
                 threshold=0,
                 lookahead=300,
                 delta=0,
                 ele_per_sec=1,
                 plot=False,
                 plot_on_mat=False,
                 sorted_peak=False,
                 corr_matrix_filename=None,
                 **kwargs):

        super(PeakPicking, self).__init__(plot, **kwargs)
        ' Raise error if parameters are not in the correct type '
        try:
            if corr_matrix is None:
                if not(corr_matrix_filename and isinstance(corr_matrix_filename, file)) \
                        or len(corr_matrix_filename.name) == 0:
                    raise TypeError("Requires corr_matrix_file to be a file")
            if corr_matrix_filename is None:
                if not (isinstance(corr_matrix, dict)):
                    raise TypeError("Requires corr_matrix to be a dictionary")
            if not (isinstance(tau_max, int)):
                raise TypeError("Requires tau_max to be an integer")
            if not (isinstance(tau_inc, int)):
                raise TypeError("Requires tau_inc to be an integer")
            if not (isinstance(threshold, float)):
                raise TypeError("Requires threshold to be an float")
            if not (isinstance(lookahead, int)):
                raise TypeError("Requires plot to be a integer")
            if not (isinstance(delta, int)):
                raise TypeError("Requires delta to be an integer")
            if not (isinstance(ele_per_sec, int)):
                raise TypeError("Requires ele_per_sec to be an integer")
            if not (isinstance(plot, bool)):
                raise TypeError("Requires plot to be a boolean")
            if not (isinstance(plot_on_mat, bool)):
                raise TypeError("Requires plot_on_mat to be an boolean")
            if not (isinstance(sorted_peak, bool)):
                raise TypeError("Requires sorted_peak to be an boolean")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        if corr_matrix is None:
            corr_matrix = dict()
        ' Raise error if parameters do not respect input rules '
        try:
            if isinstance(corr_matrix_filename, file):
                corr_matrix = json.load(corr_matrix_filename)
                if len(corr_matrix) == 0:
                    raise ValueError("Requires json file '" +
                                     corr_matrix_filename +
                                     "' to not be empty")
            if tau_max < 0:
                raise ValueError("Requires tau_max to be a positive scalar")
            if tau_inc < 0 or tau_inc > tau_max:
                raise ValueError(
                    "Requires tau_inc to be a positive scalar inferior to tau_max length"
                )
            if threshold < 0 or threshold > 1:
                raise ValueError("Requires threshold to be between 0 and 1")
            if ele_per_sec <= 0:
                raise ValueError(
                    "Requires ele_per_sec to be a strictly positive scalar")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #16
0
class PhaseSynchro_Entropy(Method):
    """
    It computes n:m synchronization index rho_nm by using a Shannon entropy based approach between two univariate signals x and y
    (in pandas DataFrame format). Rho_nm ranges in [0,1] where 0 means no synchronization at all and 1 means perfect synchronization.
   
    **Reference :**
    M. Rosenblum, A. Pikovsky, J. Kurths, C. Schafer and P. A. Tass. Phase synchronizatio:from theory to practice. In Handbook of Biological Physics,
    Elsiever Science, Series Editor A.J. Hoff, Vol. , Neuro-Informatics, Editors: F. Moss and S. Gielen, Chapter 9.
    
    :param n:
        it is the integer for the order of synchronization 
    :type n: int 
    
    :param m:
        it is the integer for the order of synchronization 
    :type m: int
    
    :param nbins_mode:
        It can be:
        1. 'auto':the number of bins will be automatically estimated
        2. 'man': the number of bins (nbins) will take the value expressed in nbins parameter
    :type nbins_mode: str
    
    :param nbins:
        it is the number of bins to be used to build phase distribution
    :type nbins: int
    
    :param dist_cyc_rel_phase:
        if True the plot of the distribution of the cyclic relative phase is returned. Default: False
    :type nbins: bool

    """
    argsList = MethodArgList()
    argsList.append('n', 1, int,
                    'it is the integer for the order of synchronization')
    argsList.append('m', 1, int,
                    'it is the integer for the order of synchronization ')
    argsList.append(
        'nbins_mode', ['auto', 'man'], list,
        'the number of bins (nbins) will be either automatically computed or specified by "nbin" paramater'
    )
    argsList.append(
        'nbins', 10, int,
        'it is the number of bins to be used to build phase distribution')
    argsList.append(
        'plot', False, bool,
        'True the plot of Q and q is returned when atype is set to tsl or asl')
    ''' Constructor '''
    def __init__(self,
                 n=1,
                 m=1,
                 nbins_mode='auto',
                 nbins=10,
                 plot=False,
                 **kwargs):
        super(PhaseSynchro_Entropy, self).__init__(plot, **kwargs)
        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(n, int)):
                raise TypeError("Requires n to be a np.array of integers")
            if not (isinstance(m, int)):
                raise TypeError("Requires m to be a np.array of integers")
            if not (isinstance(nbins_mode, str)):
                raise TypeError("Requires nbins_mode to be a string")
            if not (isinstance(nbins, int)):
                raise TypeError("Requires nbins to be an integer")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if n <= 0:
                raise ValueError("Requires n to have a size greater than 0")
            if m <= 0:
                raise ValueError("Requires n to have a size greater than 0")
            if nbins_mode != 'auto' and nbins_mode != 'man':
                raise ValueError("Requires nbins_mode to be a 'auto' or 'man'")
            if nbins <= 0:
                raise ValueError("Requires nbins to be a positive scalar")

        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #17
0
class MutualInformation(Method):
    """
    It computes Mutual Information (MI) estimators starting from entropy estimates from k-nearest-neighbours distances.
    
    **Reference :**
    
    * A.Kraskov, H.Stogbauer, and P.Grassberger. Estimating mutual information. Physical Review E, 69(6):066138, 2004
    
    :param n_neighbours:
        number of nearest neighbours  
    :type n_neighbours: int
    
    :param my_type:
        Type of the estimators will be used to compute MI. Two options (1 and 2) are available:
            1. the number of the points nx and ny is computed by taking into account only the points whose distance is stricly
            less than the distance of the k-nearest neighbours; 
            2. the number of the points nx and ny is computed by taking into account only the points whose distance is equal to
            or less than the distance of the k-nearest neighbours; 
       Default: 1 
    :type my_type: int
    
    :param var_resc:
        Boolean value indicating if the input signals should be rescaled at unitary variance. Default: False
    :type var_resc: bool
    
    :param noise:
        Boolean value indicating if a very low amplitude random noise should be added to the signals.
        It is done to avoid that there are many signals points having identical coordinates. Default: True
    :type noise: bool
        
    """
    argsList = MethodArgList()
    argsList.append('n_neighbours', 10, int,
                    'number of the nearest neighbours to be used')
    argsList.append('my_type', 1, int, 'the type of estimators [1 or 2]')
    argsList.append('var_resc', False, bool,
                    'signals should be rescaled at unitary variance')
    argsList.append('noise', True, bool,
                    'adding random noise to the time series')
    ''' Constuctor '''
    def __init__(self,
                 n_neighbours,
                 my_type=1,
                 var_resc=True,
                 noise=True,
                 **kwargs):
        super(MutualInformation, self).__init__(plot=False, **kwargs)
        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(n_neighbours, int)):
                raise TypeError("Requires n_neighbours to be an integer")
            if not (isinstance(my_type, int)):
                raise TypeError("Requires my_type to be an integer")
            if not (isinstance(var_resc, bool)):
                raise TypeError("Requires var_resc to be a boolean")
            if not (isinstance(noise, bool)):
                raise TypeError("Requires noise to be a boolean")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if n_neighbours <= 0:
                raise ValueError(
                    "Requires n_neighbours to be a positive integer greater than 0"
                )
            if my_type != 1 and my_type != 2:
                raise ValueError("Requires my_type to be to be 1 or 2")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #18
0
class Correlation(Method):
    """
    It computes the linear correlation between two univariate signals x and y (in pandas DataFrame format) as a function of their delay tau.
    It computes autocorrelation when y coincides with x.
    
    :param tau_max:
        the maximum lag (in samples) at which correlation should be computed. It is in the range [0; (length(x)+length(y)-1)/2] 
    :type tau_max: int
    
    :param plot:
        if True the plot of correlation function is returned. Default: False
    :type plot: bool
    
    :param standardization:
        if True the inputs are standardize to mean 0 and variance 1. Default: False
    :type standardization: bool
    
    :param corr_tau_max:
        if True the maximum of correlation and its lag are returned. Default: False
    :type corr_tau_max: bool
    
    :param corr_coeff:
        if True the correlation coefficient (Pearson's version) is computed. It is enabled only if the parameter standardize is True. Default: False
    :type corr_coeff: bool
    
    :param scale:
        if True the correlation function is scaled in the range [-1;1]
    :type scale: bool
    """
    argsList = MethodArgList()
    argsList.append(
        'tau_max', 0, int,
        'the maximum lag (in samples) at which correlation should be computed')
    argsList.append(
        'standardization', False, bool,
        'if True the inputs are standardize to mean 0 and variance 1')
    argsList.append(
        'corr_tau_max', False, bool,
        'if True the maximum of correlation and its lag are returned')
    argsList.append(
        'corr_coeff', False, bool,
        'if True the correlation coefficient (Pearson\'s version) is computed')
    argsList.append(
        'scale', False, bool,
        'if True the correlation function is scaled in the range [-1;1]')
    argsList.append('plot', False, bool,
                    'if True the plot of correlation function is returned')
    ''' Constructor '''
    def __init__(self,
                 tau_max,
                 plot=False,
                 standardization=False,
                 corr_tau_max=False,
                 corr_coeff=False,
                 scale=False,
                 **kwargs):
        super(Correlation, self).__init__(plot, **kwargs)

        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(tau_max, int)):
                raise TypeError("Requires tau_max to be an integer")
            if not (isinstance(plot, bool)):
                raise TypeError("Requires plot to be a boolean")
            if not (isinstance(standardization, bool)):
                raise TypeError("Requires standardization to be a boolean")
            if not (isinstance(corr_tau_max, bool)):
                raise TypeError("Requires corr_tau_max to be a boolean")
            if not (isinstance(corr_coeff, bool)):
                raise TypeError("Requires corr_coeff to be a boolean")
            if not (isinstance(scale, bool)):
                raise TypeError("Requires scale to be a boolean")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if tau_max < 0:
                raise ValueError(
                    "Requires tau_max to be a strictly positive scalar")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #19
0
class PartialCoherence(Method):
    """
    It computes the partial coherence in a list of signals, 3 signals at a time.
    
    **Reference :**
    
    * Pereda, E. and al., Nonlinear multivariate analysis of neurophysiological signals. Progress in Neurobiology 77 (2005) I-37.
    
  :param fs:
    sampling frequency (in Hz) of the input signal. Default: 1.0
  :type fs: float
  
  :param NFFT:
    length of each epoch (in samples). Default: 256
  :type NFFT: int
  
  :param detrend:
    it specifies which kind of detrending should be computed on data. Ranges in [0;1]:
        1. 0 constant detrending;
        2. 1 linear detrending.
    Default: 0
  :type detrend: int
  
  :param noverlap:
    number of samples to overlap between epochs. Default: 0
  :type noverlap: int
    """
    argsList = MethodArgList()
    argsList.append('fs', 1.0, float,
                    'Sampling frequency (in Hz) of the input signal')
    argsList.append('NFFT', 256, int, 'Length of each epoch (in samples)')
    argsList.append(
        'detrend', [0, 1], list,
        'Specifies which kind of detrending should be computed on data. Ranges in [0;1] (0 for constant, 1 for linear)'
    )
    argsList.append('noverlap', 0, int,
                    'Number of samples to overlap between epochs')
    ''' Constructor '''
    def __init__(self,
                 fs=1.0,
                 NFFT=256,
                 detrend=0,
                 noverlap=0,
                 plot=False,
                 **kwargs):
        super(PartialCoherence, self).__init__(plot, **kwargs)
        #In the constructor we can check that params have corrects values and initialize stuff

        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(fs, float)):
                raise TypeError("Requires fs to be an float")
            if not (isinstance(NFFT, int)):
                raise TypeError("Requires NFFT to be an integer")
            if isinstance(detrend, str): detrend = int(detrend)
            if not (isinstance(detrend, int)):
                raise TypeError("Requires detrend to be an integer")
            if not (isinstance(noverlap, int)):
                raise TypeError("Requires noverlap to be an integer")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if fs < 0: raise ValueError("Requires fs to be a positive scalar")
            if NFFT <= 0:
                raise ValueError(
                    "Requires NFFT to be a strictly positive scalar")
            if NFFT % 2 != 0:
                raise ValueError("Requires NNFT to be a multiple of 2")
            if detrend != 0 and detrend != 1 and detrend != 2:
                raise ValueError("Requires detrend to be 0, 1 or 2")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #20
0
class WindowMutualInformation(Method):
    """
    It computes Windowed Mutual Information (MI) estimators starting from entropy estimates from k-nearest-neighbours distances.
    
    **Reference :**
    
    * A.Kraskov, H.Stogbauer, and P.Grassberger. Estimating mutual information. Physical Review E, 69(6):066138, 2004
    
    :param n_neighbours:
        number of nearest neighbours  
    :type n_neighbours: int
    
    :param my_type:
        Type of the estimators will be used to compute MI. Two options (1 and 2) are available:
            1. the number of the points nx and ny is computed by taking into account only the points whose distance is stricly
            less than the distance of the k-nearest neighbours; 
            2. the number of the points nx and ny is computed by taking into account only the points whose distance is equal to
            or less than the distance of the k-nearest neighbours; 
       Default: 1 
    :type my_type: int
    
    :param var_resc:
        Boolean value indicating if the input signals should be rescaled at unitary variance. Default: True
    :type var_resc: bool
    
    :param noise:
        Boolean value indicating if a very low amplitude random noise should be added to the signals.
        It is done to avoid that there are many signals points having identical coordinates. Default: True
    :type noise: bool
    
    :param tau_max:
        the maximum lag (in samples) at which correlation should be computed. It is in the range [0; (length(x)+length(y)-1)/2] 
    :type tau_max: int
    
    :param window:
        length (in samples) of the windowed signals 
    :type window: int
    
    :param win_inc:
        amount of time (in samples) elapsed between two windows 
    :type win_inc: int
    
    :param tau_inc:
        amount of time (in samples) elapsed between two cross-correlation 
    :type tau_inc: int
    
    :param plot:
        if True the plot of correlation function is returned. Default: False
    :type plot: bool
        
    """
    argsList = MethodArgList()
    argsList.append('n_neighbours', 5, int, 'number of nearest neighbours')
    argsList.append(
        'my_type', 1, int,
        'type of the estimators will be used to compute MI (1 or 2)')
    argsList.append('var_resc', True, bool,
                    'input signals should be rescaled at unitary variance')
    argsList.append('noise', True, bool,
                    'random noise should be added to the signals')
    argsList.append(
        'tau_max', 10, int,
        'maximum lag (in samples), range [0; (length(x)+length(y)-1)/2]')
    argsList.append('window', 10, int,
                    'length (in samples) of the windowed signals')
    argsList.append('win_inc', 1, int,
                    'amount of time (in samples) elapsed between two windows')
    argsList.append(
        'tau_inc', 1, int,
        'amount of time (in samples) elapsed between two cross-correlation')
    argsList.append('plot', False, bool,
                    'plot the correlation function or not')
    ''' Constuctor '''
    def __init__(self,
                 n_neighbours,
                 my_type=1,
                 var_resc=True,
                 noise=True,
                 tau_max=0,
                 window=0,
                 win_inc=1,
                 tau_inc=1,
                 plot=False,
                 **kwargs):

        ' Raise error if parameters are not in the correct type '
        super(WindowMutualInformation, self).__init__(plot, **kwargs)

        try:
            if not (isinstance(n_neighbours, int)):
                raise TypeError("Requires n_neighbours to be an integer")
            if not (isinstance(my_type, int)):
                raise TypeError("Requires my_type to be an integer")
            if not (isinstance(var_resc, bool)):
                raise TypeError("Requires var_resc to be a boolean")
            if not (isinstance(noise, bool)):
                raise TypeError("Requires noise to be a boolean")
            if not (isinstance(tau_max, int)):
                raise TypeError("Requires tau_max to be an integer")
            if not (isinstance(window, int)):
                raise TypeError("Requires window to be an integer")
            if not (isinstance(win_inc, int)):
                raise TypeError("Requires win_inc to be an integer")
            if not (isinstance(tau_inc, int)):
                raise TypeError("Requires tau_inc to be an integer")
            if not (isinstance(plot, bool)):
                raise TypeError("Requires plot to be a boolean")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if n_neighbours <= 0 or n_neighbours >= window:
                raise ValueError(
                    "Requires n_neighbours to be a positive integer greater than 0 inferior to window length"
                )
            if my_type != 1 and my_type != 2:
                raise ValueError("Requires my_type to be to be 1 or 2")
            if tau_max < 0:
                raise ValueError("Requires tau_max to be a positive scalar")
            if window < 0:
                raise ValueError("Requires window to be a positive scalar")
            if win_inc < 0 or win_inc >= window:
                raise ValueError(
                    "Requires win_inc to be a positive scalar inferior to window length"
                )
            if tau_inc < 0 or tau_inc > tau_max:
                raise ValueError(
                    "Requires tau_inc to be a positive scalar inferior to tau_max length"
                )
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #21
0
class ConditionalGrangerCausality(Method):
    """
    It computes a bi-directional pairwise Granger causality test between all the signals, to detect temporary direct links.
    For each detected link, a conditional test is made to know if the link between the two signals is mediated by another signal.
    At the end of the test, a node graphic is shown to see the links between the signals.

    **Reference :**

    * XiaotongWen, Govindan Rangarajan, and Mingzhou Ding. Univariate Granger causality : an estimation framework based on factorization of the spectral density matrix. Philosophical Transactions of the Royal Society of London A : Mathematical, Physical and Engineering Sciences, 371(1997) :20110610, August 2013.

    :param max_lag:
        The number of maximum lag (in samples) with which the autoregressive model will be computed.
        It ranges in [1;length(x)]. Default :1.
    :type max_lag: int

    :param criterion: A string that contains the name of the selected criterion to estimate optimal number of lags value.
        Two choices are possible :
            1. 'bic' (Bayesian Information Criterion);
            2. 'aic' (Akaike information criterion)
        Default : 'bic'
    :type criterion: str

    :param plot:
        if True the plot of correlation function is returned. Default: False
    :type plot: bool
    """
    argsList = MethodArgList()
    argsList.append(
        'max_lag', 1, int,
        'The number of maximum lag (in samples) with which the autoregressive model will be computed. It ranges in [1;length(x)]'
    )
    argsList.append('criterion', ['bic', 'aic'], list,
                    'criterion to estimate optimal number of lags value')
    argsList.append('plot', False, bool, ' plot of correlation function ')
    ''' Constructor '''
    def __init__(self, max_lag=1, criterion='bic', plot=False, **kwargs):
        super(ConditionalGrangerCausality, self).__init__(plot, **kwargs)

        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(criterion, str)):
                raise TypeError("Requires criterion to be a str")
            if not (isinstance(max_lag, int)):
                raise TypeError("Requires max_lag to be an int")
            if not (isinstance(plot, bool)):
                raise TypeError("Requires plot to be a bool")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '

        try:
            if max_lag <= 0:
                raise ValueError(
                    "Requires max_lag to be a strictly positive scalar")
            if criterion != 'bic' and criterion != 'aic':
                raise ValueError("Requires criterion to be 'bic' or 'aic'")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #22
0
class Coherence(Method):
    """
  It computes the linear correlation between two univariate signals x and y (in pandas DataFrame format) as a function of the frequency.
  It is the cross-spectral density function normalized by the autospectral density function of x and y.
  
   **Reference :**
   
   * Inspired by a John Hunter's Python code 
  
  :param fs:
    sampling frequency (in Hz) of the input DataFrame . Default: 1.0
  :type fs: float
  
  :param NFFT:
    length (in samples) of each epoch. Default: 256
  :type NFFT: int
  
  :param detrend:
    it specifies which kind of detrending should be computed on the inout. It ranges in [0;2]:
        1. 0 no detrending;
        2. 1 constant detrending;
        3. 2 linear detrending.
    Default: 0
  :type detrend: int
  
  :param noverlap:
    number of sampels to overlap between epochs. Default: 0
  :type noverlap: int
  
  :param plot:
    if True the plot of coherence function is returned. Default: False
  :type plot: bool
  """
    argsList = MethodArgList()
    argsList.append('fs', 1.0, float,
                    'sampling frequency (in Hz) of the input DataFrame')
    argsList.append('NFFT', 256, int, 'length (in samples) of each epoch')
    argsList.append(
        'detrend', 0, int,
        'which kind of detrending should be computed on the inout [0;2]')
    argsList.append('noverlap', 0, int,
                    'number of sampels to overlap between epochs')
    argsList.append('plot', False, bool,
                    'if True the plot of coherence function is returned')
    ''' Constructor '''
    def __init__(self,
                 fs=1.0,
                 NFFT=256,
                 detrend=0,
                 noverlap=0,
                 plot=False,
                 **kwargs):
        super(Coherence, self).__init__(plot, **kwargs)

        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(fs, float)):
                raise TypeError("Requires fs to be an float")
            if not (isinstance(NFFT, int)):
                raise TypeError("Requires NFFT to be an integer")
            if not (isinstance(detrend, int)):
                raise TypeError("Requires detrend to be an integer")
            if not (isinstance(noverlap, int)):
                raise TypeError("Requires noverlap to be an integer")
            if not (isinstance(plot, bool)):
                raise TypeError("Requires plot to be a boolean")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if parameters do not respect input rules '
        try:
            if (detrend != 0) and (detrend != 1) and (detrend != 2):
                raise ValueError("Requires detrend to be 0 or 1 or 2")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return
Пример #23
0
class CCA(Method):
    """
    It extracts the highest correlations possible between linear combinations of the features of the two multivariate signals.
    These signals must contain the same number of row (samples), but
    can contain a different number of features (i.e different number of colums)

    **reference paper** :

      - David Weenink, Canonical correlation analysis
      - Karl Stratos, A Hitchhiker’s Guide to PCA and CCA
      - Alvin C. Rencher, Methods of Multivariate Analysis
      - Mehmet Emre Sargin, Audiovisual Synchronization and Fusion Using Canonical Correlation Analysis

     to see the algorithm on 2 exemples see CCA_simple and CCA_signals in SyncPy-master/expemples

     inputs : Due to technical constraints(graphical issues) the two signals to be processed are passed as contructor's parameters

     :param nbr_correlations: is the number of maximized correlation you want to have at the end
     default 0 means you choose the minimum between the number of features of your two multivariate signals

     :param Synchrony: if True it means that you want to seek if by shifting a little bit your two multivariate signals you will find a better synchrony
     between them.
     default False

     :param Proportion: integer between 0 and 20, represent the proportion of lag you are willing to investigate synchrony on
     default 0: 20% of time lag is used if Synchrony is True

     :param plot: if True gives the distribution of the score(as define bellow) of your Synchrony search


    returns:

    :res['xWeights'] and res['xWeights']: the weights of the linear combinations

    :res['corr']: squared correlations that comes with those weights (length of this array is define by nbr_correlations)

    :res['score']: score is the sum of the squared maximised correlations (with no shift)

    :res['scoreMax']: scoreMax is the score (as define above) maximal that we can find by shifting the two datasets

    :res['shift']: How should we shift the first dataset w.r.t the second to find the scoreMax

    :res{'storage']: is mainly used to plot the distributions of the different score through the shifting process

    """

    argsList = MethodArgList()
    argsList.append('ignoreInputSignals', True, bool,
                    'Data really comes from the file below', True)
    argsList.append('xData_filename', '', file, 'First data set in cvs format')
    argsList.append('yData_filename', '', file,
                    'Second data set in cvs format')
    argsList.append('nbr_correlations', 0, int,
                    'number of maximised correlations wanted')
    argsList.append('Synchrony', False, bool,
                    'Do we look for optimal Synchrony')
    argsList.append('Proportion', 0, int, 'how the decay can maximally happen')
    argsList.append(
        'plot', False, bool,
        'if True and Synchrony is on toot, the plot of coherence function is returned'
    )

    def __init__(self,
                 ignoreInputSignals=True,
                 nbr_correlations=0,
                 xData=None,
                 yData=None,
                 xData_filename=None,
                 yData_filename=None,
                 Synchrony=False,
                 Proportion=0,
                 plot=False,
                 **kwargs):
        ' Init '
        super(CCA, self).__init__(plot, **kwargs)
        if xData is None:
            if not (xData_filename and isinstance(xData_filename, file)) \
                    or len(xData_filename.name) == 0:
                raise TypeError("Requires xData_filename to be a file")

        if yData is None:
            if not (yData_filename and isinstance(yData_filename, file)) \
                    or len(yData_filename.name) == 0:
                raise TypeError("Requires yData_filename to be a file")

        if not (isinstance(nbr_correlations, int)):
            raise TypeError("Requires m to be an integer")
        # other rule for parameters
        if nbr_correlations < 0:
            raise ValueError("Requires m to be positive or greater than 0")

        if isinstance(xData_filename, file):
            xData = pd.DataFrame.from_csv(xData_filename)

        if isinstance(yData_filename, file):
            yData = pd.DataFrame.from_csv(yData_filename)
        if not (isinstance(Synchrony, bool)):
            raise TypeError("Synchrony must be a boolean")
        if not (isinstance(plot, bool)):
            raise TypeError("plot must be a boolean")
        if (Proportion > 0 and Synchrony == False):
            raise ValueError(
                "you can't havea positiv proportion if you do not seek synchrony"
            )
        if (Synchrony == True and Proportion == 0): Proportion = 20
        if (Proportion < 0 or Proportion > 20):
            raise ValueError("Proportion must be between 0 and 20 purcents")

        if not (isinstance(xData, pd.DataFrame)):
            raise TypeError("Requires xData to be a panda dataframe")
        if not (isinstance(yData, pd.DataFrame)):
            raise TypeError("Requires yData to be a panda dataframe")

        self._xData = xData
        self._yData = yData
        self._nbr_correlations = nbr_correlations
        self.sync = Synchrony
        self.proportion = Proportion
        self.lx = None
        self.ly = None
        self._plot = plot
        return

    def plot_result(self, result):
        """
        It plots the cca function if you are lokking for synchrony between two signals

        :param result:
             storage from compute()
        :type result: dict

        :returns: plt.figure
         -- figure plot
        """

        ' Raise error if parameters are not in the correct type '
        try:
            if not (isinstance(result, dict)):
                raise TypeError("Requires result to be a dictionary")
        except TypeError, err_msg:
            raise TypeError(err_msg)
            return

        ' Raise error if not the good dictionary '
        try:
            if not 'storage' in result:
                raise ValueError(
                    "Requires storage to be the output of compute() method")
        except ValueError, err_msg:
            raise ValueError(err_msg)
            return