Beispiel #1
0
def flatten_tcs(A,dof='EstEff'):
    """ Concat timecourses, demeaning, estimating dof """
    tcs_dm=pl.demean(A.tcs,2)
    shp=tcs_dm.shape
    out=FC((np.reshape(tcs_dm.swapaxes(0,1),[shp[1],-1])),ROI_info=A.ROI_info)
    # subtract dofs from demeaning 
    out.dof=out.dof-shp[0]
    tcs = out.tcs

    if dof is None:
        self.dof=tcs.shape[-1]-1
    elif dof == 'EstEff':
        AR=np.zeros((tcs.shape[0],tcs.shape[1],15))
        ps=np.zeros((tcs.shape[0],tcs.shape[1],15))
        for subj in np.arange(tcs.shape[0]): 
            for ROI in np.arange(tcs.shape[1]):
                AR[subj,ROI,:]=spectrum.aryule(pl.demean(tcs[subj,ROI,:]),15)[0]
                ps[subj,ROI,:]=spectrum.correlation.CORRELATION(pl.demean(tcs[subj,ROI,:]),maxlags=14,norm='coeff')
        ps = np.mean(np.mean(ps,0),0)
        AR = np.mean(np.mean(AR,0),0)
        dof_nom=tcs.shape[-1]-1
        dof = int(dof_nom / (1-np.dot(ps[:15].T,AR))/(1 - np.dot(np.ones(len(AR)).T,AR)))

    out.dof=dof

    return(out)
def predlin(s,p,w):
    """
    Function that computes de linear prediction using lpc for a given signal
    """
    x = s*w
    
    lpc,e = spectrum.lpc(x,N = p)
    #E = np.sqrt(np.sum(x**2))
    ar,sigma,lt = spectrum.aryule(x,p)
    
    
    plt.subplot(3,1,1)
    plt.plot(s)
    plt.title("Speech signal")
    xx = np.arange(0,len(w))
    plt.plot(xx,w*np.max(s))

    plt.subplot(312)
    plt.plot(x)
    plt.title("Windowed signal")
    
    plt.subplot(313)
    S_x = 20*np.log10(np.abs(np.fft.fft(x,2*len(w))))
    plt.plot(S_x[0:len(w)])
    ff,h = scipy.signal.freqz(1,ar,len(w),whole=False)
    h2 = spectrum.arma2psd(ar,NFFT=len(w)*2)
    plt.plot(20*np.log10(np.abs(h2[0:len(w)])))
Beispiel #3
0
def Spectrum(Data):
    Data[Data < 0] = 0
    ar, variance, coeff_reflection = aryule(Data, 5)
    plt.figure()
    plt.stem(range(len(ar)), ar)
    plt.show()
    plt.figure()
    Residual = Data - np.mean(Data)
    plt.hist(Residual)
    return ar
    def ar_model(self, ):  # another way
        # AR model using the Yule-Walker (autocorrelation) method
        self.ar, self.var, self.reflec = spectrum.aryule(
            np.array(self.xw), 30, allow_singularity=True)
        if self.Flag_Show:
            print('a=', self.ar)

        self.psd_ar = spectrum.arma2psd(A=self.ar, NFFT=self.NFFT, norm=False)
        self.psd2_ar = self.psd_ar[0:int(len(self.psd_ar) /
                                         2)]  # get half side
Beispiel #5
0
def main():
    sns.set_style('darkgrid')
    s = load_emg(
        r'C:\Users\win10\Desktop\Projects\CYB\Experiment_Balint\CYB004\Data',
        task='Walk')
    s = norm_emg(s)
    # def f(x_in):
    #     n, x, x_hat, e, ao, F, Ao = lms_ic(3, x_in, s[7,:], mu=0.01)
    #     return e
    # s_filt = np.apply_along_axis(f, 1, s[0:7, :])
    # s[0:7, :] = s_filt

    PACs = list()
    count = 0
    for sig in s:
        count += 1
        print(count)
        PAC = list()
        _, _, coeff_reflection = aryule(sig, 15)
        PACs.append(coeff_reflection)

    fig, axes = plt.subplots(4, 2)
    fig.suptitle("Partial Autocorrelation Functions")
    axes = axes.flatten()
    muscle_names = [
        'L Internal Oblique', 'R Internal Oblique', 'L External Oblique',
        'R External Oblique', 'Latissimus Dorsi', 'Transverse Trapezius',
        'Erector Spinae', 'ECG'
    ]
    for i, ax in enumerate(axes):
        x, _, _ = ax.stem(np.arange(6, 16),
                          PACs[i][5:],
                          use_line_collection=True,
                          basefmt='grey')
        x.set_label(muscle_names[i])
        l = ax.axhline(1.96 / np.sqrt(s.shape[1]), color='tab:orange', ls='--')
        l.set_label('95% confidence interval')
        ax.axhline(-1.96 / np.sqrt(s.shape[1]), color='tab:orange', ls='--')
        if i % 2 is 0:
            ax.set_ylabel('PAC')
        if i < 6:
            ax.set_xticks(np.arange(6, 16, 2))
            ax.set_xticklabels([])
        else:
            ax.set_xticks(np.arange(6, 16, 2))
            ax.set_xlabel("Lag")
        x.set_markersize(4)
        ax.legend()

    plt.tight_layout()
    plt.subplots_adjust(top=0.95)
    plt.show()
def get_ar_aic(data, order=3, n_win=100, s_win=100):
    data_len = len(data)
    aic = np.zeros(data_len, dtype=np.float32)
    An = aryule(data[:n_win], order)[0]
    As = aryule(data[data_len - s_win:], order)[0]
    An = An * -1
    As = As * -1
    for i in range(data_len):
        if i <= order or i >= data_len - order:
            aic[i] = 1e7
            continue
        var_before = 0
        for j in range(order, i + 1):
            var_before += (data[j] -
                           np.dot(An, data[j - order:j]))**2 / (i + 1 - order)
        var_after = 0
        for j in range(i + 1, data_len - order + 1):
            var_after += (data[j] - np.dot(As, data[j - order:j]))**2 / (
                data_len - order - i)
        aic[i] += (i - order) * np.log(var_before + 0.1) + (
            data_len - order - i) * np.log(var_after + 0.1)

    return aic
Beispiel #7
0
    def __init__(self,tcs,cov_flag=False,dof=None,ROI_info={},mask=None):
        """  Initialise the FC object. """
        #  reading covariance matrix
        if cov_flag==True:
            self.tcs=None

            covs=tcs
            
            if dof is None:
                raise ValueError("Need to specify dof if providing cov.")
            else:
                self.dof=dof
  
        else:
            # reading timecourses
            if tcs.ndim==2:
                tcs=(np.atleast_3d(tcs).transpose(2,0,1))
            
            self.tcs = tcs
            if dof is None:
                self.dof=tcs.shape[-1]-1
            elif dof == 'EstEff':
                AR=np.zeros((tcs.shape[0],tcs.shape[1],15))
                ps=np.zeros((tcs.shape[0],tcs.shape[1],15))
                for subj in np.arange(tcs.shape[0]): 
                    for ROI in np.arange(tcs.shape[1]):
                        AR[subj,ROI,:]=spectrum.aryule(pl.demean(tcs[subj,ROI,:]),15)[0]
                        ps[subj,ROI,:]=spectrum.correlation.CORRELATION(pl.demean(tcs[subj,ROI,:]),maxlags=14,norm='coeff')
                ps = np.mean(np.mean(ps,0),0)
                AR2 = np.mean(np.mean(AR,0),0)
                dof_nom=tcs.shape[-1]-1
                self.dof = int(dof_nom / (1-np.dot(ps[:15].T,AR2))/(1 - np.dot(np.ones(len(AR2)).T,AR2)))
            else:
                self.dof=dof

            covs = get_covs(tcs)

        if ROI_info=={}:
            shp=covs.shape[-1]
            ROI_info['ROI_names']=np.arange(shp).astype(str)
            ROI_info['ROI_RSNs']=np.ones(shp,).astype(int)

        if mask:
            self.mask=mask

        self.ROI_info = ROI_info

        self.covs = covs
Beispiel #8
0
    def extract_features(self, data_input):
        """ Autoregressive Coefficient
        "This feature models individual EMG signals as a linear
        autoregressive time series and provides information
        about the muscle's contraction state" (Tkach et. al 5)

        uses time-series analysis library spectrum to compute single
        order autoregressive model coefficients using Yule-Walker equations for each
        channel and contructs an array made up of the autoregressive coeffcients (a sub 1 since only first order)
        for each channel

        :param data_input: input samples to compute feature
        :return: feature value
        """

        ar_feature = []
        for channel in range(8):
            ar_coefficient_array, noise, reflection = aryule(np.hstack(data_input[:, channel:channel+1]), 1)
            ar_coefficient = ar_coefficient_array[0]
            ar_feature.append(ar_coefficient)

        return ar_feature
Beispiel #9
0
    def extract_features(self, data_input):
        """ Cepstrum coefficients
        "This measure provides information about the rate of
        change in different frequency spectrum bands of a signal." (Tkach et. al 5)

        since c sub 1 = -a sub 1, this will be the case for all channels since first order
        uses time-series analysis library spectrum to compute single
        order autoregressive model coefficients using Yule-Walker equations for each
        channel and contructs an array made up of the cepstrum coeffcients (-a sub 1 since only first order)
        for each channel

        :param data_input: input samples to compute feature
        :return: scalar feature value

        """

        ceps_feature = []
        for channel in range(8):
            ar_coefficient_array, noise, reflection = aryule(np.hstack(data_input[:, channel:channel+1]), 1)
            ar_coefficient = ar_coefficient_array[0]
            ceps_coefficient = -ar_coefficient
            ceps_feature.append(ceps_coefficient)

        return ceps_feature
Beispiel #10
0
def create_all_psd():


    f = pylab.linspace(0, 1, 4096)
    pylab.clf()

    pylab.figure(figsize=(12,8))

    #MA 15 order
    b, rho = spectrum.ma(data, 15, 30)
    psd = spectrum.arma2psd(B=b, rho=rho)
    newpsd = tools.cshift(psd, len(psd)//2) # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd/max(newpsd)), label='MA 15')

    #ARMA 15 order
    a, b, rho = spectrum.arma_estimate(data, 15,15, 30)
    psd = spectrum.arma2psd(A=a,B=b, rho=rho)
    newpsd = tools.cshift(psd, len(psd)//2) # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd/max(newpsd)), label='ARMA 15,15')

    #yulewalker
    ar, P,c = spectrum.aryule(data, 15, norm='biased')
    psd = spectrum.arma2psd(A=ar, rho=P)
    newpsd = tools.cshift(psd, len(psd)//2) # switch positive and negative freq

    pylab.plot(f, 10 * pylab.log10(newpsd/max(newpsd)), label='YuleWalker 15')

    #burg method
    ar, P,k = spectrum.arburg(data, order=15)
    psd = spectrum.arma2psd(A=ar, rho=P)
    newpsd = tools.cshift(psd, len(psd)//2) # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd/max(newpsd)), label='Burg 15')

    #covar method
    af, pf, ab, pb, pv = spectrum.arcovar_marple(data, 15)
    psd = spectrum.arma2psd(A=af, B=ab, rho=pf)
    newpsd = tools.cshift(psd, len(psd)//2) # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd/max(newpsd)), label='covar 15')

    #modcovar method
    a, p, pv = spectrum.modcovar_marple(data, 15)
    psd = spectrum.arma2psd(A=a)
    newpsd = tools.cshift(psd, len(psd)//2) # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd/max(newpsd)), label='modcovar 15')

    #correlogram
    psd = spectrum.CORRELOGRAMPSD(data, data, lag=15)
    newpsd = tools.cshift(psd, len(psd)/2) # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd/max(newpsd)), label='correlogram 15')

    #minvar
    psd = spectrum.minvar(data, 15)
    #newpsd = tools.cshift(psd, len(psd)/2) # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd/max(newpsd)), label='MINVAR 15')

    #music
    psd,db = spectrum.music(data, 15, 11)
    pylab.plot(f, 10 * pylab.log10(psd/max(psd)), '--',label='MUSIC 15')

    #ev music
    psd,db = spectrum.ev(data, 15, 11)
    pylab.plot(f, 10 * pylab.log10(psd/max(psd)), '--',label='EV 15')


    pylab.legend(loc='upper left', prop={'size':10}, ncol=2)
    pylab.ylim([-80,10])
    pylab.savefig('psd_all.png')
Beispiel #11
0
plt.ylabel("h_y_dimp")
plt.title(
    "Fig:6  Risp. impuls.: 'h_y_dimp ricalc' con dimpulse da: 'B_y(z)', 'A_y(z)'"
)
plt.axis(v)

#=========================================================\
# 12) Modelli vari AR

#=================  ARYULE agorithm === (ECCEZIONALE *****) ==========
#     Modello AR(MA) di Yule-Walker: dalla risposta impulsiva
#     ricava un sistema a(z), questo modello ha 1 solo parametro: il n_zeri.
#
model_type = "ARYULE"
Ar_y_calc = np.zeros(N)
a, e, Ar_y_calc[0:N - 1] = aryule(h_a_calc,
                                  N - 1)  # equals the following 2 lines
### R = xcorr(h_a_calc, N,'biased');
### [a, e, Ar_y_calc] = levinson(R(N+1:end), N);    # levinson is a MEX compiled function
#====================================================================

#==========  AR Burg agorithm === (SPORCO E RITORNA IL DOPPIO !! ! ) ====
# Con filtri LP  da' risultati quando gli altri modelli divergono!
#
#model_type = "ARBURG"
#Ar_y_calc = np.zeros(N)
#a, e, Ar_y_calc = arburg(h_a_calc, N)
#Ar_y_calc       = Ar_y_calc / 2
### Ar_y_calc = Ar_y_calc(1,:)'; # returns a 2rows vect., 2nd row is a constant value!?
### Ar_y_calc = [Ar_y_calc; Ar_y_calc(N)]; Ar_y_calc = Ar_y_calc(2: N+1); # Shift left

#==========  Codice scritto ex novo: Collomb's C++ code, pp. 10-11 ====
Beispiel #12
0
ica.plot_overlay(raw, exclude=[0, 2, 11, 19, 21, 24, 30,
                               33])  #plot the proposed transformation
ica.apply(raw, exclude=[0, 2, 11, 19, 21, 24, 30,
                        33])  #apply the transformation

'Change-able variables'
channeltopick = 49
thetathreshold = 0.5

'Pick 1 channel'
(newdata, newtimes) = raw[::, ::]
channel1data = newdata[channeltopick, ::]  #pick a single channel

'pick order based on AIC, takes a long time'
order = arange(2, 100)
rho = [spectrum.aryule(channel1data, i, norm='biased')[1] for i in order]
plt.plot(order, spectrum.AIC(len(last1second), rho, order), label='AIC')
index_min = np.argmin(spectrum.AIC(len(last1second), rho,
                                   order))  #pick minimum rho
plt.title(index_min)

'choose just 1 second of 1 channel'
for abba in totaltrials:  #for loop to do multiple second chunks
    choiceofsecond = 6
    last1second = channel1data[-500 * choiceofsecond:-500 *
                               (choiceofsecond - 1)]  #pick a second chunk
    last1second = last1second - mean(last1second)  #remove mean
    plot(last1second)

    'autoregressive spectral analysis'
    [ar, var, reflec] = spectrum.aryule(last1second, index_min, norm='biased')
Beispiel #13
0
def obtain_ar_coefficients(data, burg_order):
    ar, _, _ = aryule(data, order=burg_order)
    return ar
Beispiel #14
0
phaseerror = [0] * 500

'Create cosine wave with noise, bandpass filtered between 0.1 and 70, mean subtracted'
noise = np.random.normal(0, 1, 512 * 500)
frequency = 512
f = 6
sample = 512 * 500
x = np.arange(sample)
#y = np.cos(2 * np.pi * f * x[:-512] / Fs) + noise
#y = np.cos(2 * np.pi * f * x[:-512] / frequency)
realsignal = np.cos(2 * np.pi * f * x / frequency)
noisysignal = realsignal + noise

'AIC'
order = arange(2, 100)
rho = [spectrum.aryule(noisysignal, i, norm='biased')[1] for i in order]
plt.plot(order, spectrum.AIC(len(noisysignal), rho, order), label='AIC')
index_min = np.argmin(spectrum.AIC(len(noisysignal), rho,
                                   order))  #pick minimum rho
plt.title(index_min)

for trials in trialnumbers:
    y = noisysignal[512 * trials:512 * (trials + 1)]

    b, a = signal.butter(1, [0.1 / (0.5 * 512), 70 / (0.5 * 512)],
                         btype='band')
    last1second = signal.filtfilt(b, a, y)
    last1second = last1second - mean(last1second)

    'Run algorithm'
    [ar, var,
Beispiel #15
0
 def featureAR(ch):
     ar_coeffs, dnr, reflection_coeffs = spectrum.aryule(ch, order=8)
     return np.abs(ar_coeffs)
def aryule(x, p):
    """From MATLAB:
    %   A = ARYULE(X,ORDER) returns the polynomial A corresponding to the AR
    %   parametric signal model estimate of vector X using the Yule-Walker
    %   (autocorrelation) method.  ORDER is the model order of the AR system. 
    %   This method solves the Yule-Walker equations by means of the Levinson-
    %   Durbin recursion.
    %
    %   [A,E] = ARYULE(...) returns the final prediction error E (the variance
    %   estimate of the white noise input to the AR model).
    %
    %   [A,E,K] = ARYULE(...) returns the vector K of reflection coefficients.
    
    Using spectrum aryule:
    def aryule(X, order, norm='biased', allow_singularity=True):
        Compute AR coefficients using Yule-Walker method
        
        :param X: Array of complex data values, X(1) to X(N)
        :param int order: Order of autoregressive process to be fitted (integer)
        :param str norm: Use a biased or unbiased correlation.
        :param bool allow_singularity: 
        
        :return:
        * AR coefficients (complex)
        * variance of white noise (Real)
        * reflection coefficients for use in lattice filter 
    """
    [A, E, K] = spectrum.aryule(x, p)
    A = np.hstack((1, A)) # MATLAB adds the first "1.0"
    return A, E, K

    # Local Variables: a, e, k, nx, p, R, x, mx
    # Function calls: aryule, nargchk, min, issparse, nargin, length, isempty, error, levinson, message, xcorr, round, size
    #%ARYULE   AR parameter estimation via Yule-Walker method.
    #%   A = ARYULE(X,ORDER) returns the polynomial A corresponding to the AR
    #%   parametric signal model estimate of vector X using the Yule-Walker
    #%   (autocorrelation) method.  ORDER is the model order of the AR system. 
    #%   This method solves the Yule-Walker equations by means of the Levinson-
    #%   Durbin recursion.
    #%
    #%   [A,E] = ARYULE(...) returns the final prediction error E (the variance
    #%   estimate of the white noise input to the AR model).
    #%
    #%   [A,E,K] = ARYULE(...) returns the vector K of reflection coefficients.
    #%   
    #%   % Example:
    #%   %   Estimate model order using decay of reflection coefficients.
    #%
    #%   rng default;
    #%   y=filter(1,[1 -0.75 0.5],0.2*randn(1024,1));
    #%
    #%   % Create AR(2) process
    #%   [ar_coeffs,NoiseVariance,reflect_coeffs]=aryule(y,10);
    #%
    #%   % Fit AR(10) model
    #%   stem(reflect_coeffs); axis([-0.05 10.5 -1 1]);
    #%   title('Reflection Coefficients by Lag'); xlabel('Lag');
    #%   ylabel('Reflection Coefficent');
    #%
    #%   See also PYULEAR, ARMCOV, ARBURG, ARCOV, LPC, PRONY.
    #%   Ref: S. Orfanidis, OPTIMUM SIGNAL PROCESSING, 2nd Ed.
    #%              Macmillan, 1988, Chapter 5
    #%        M. Hayes, STATISTICAL DIGITAL SIGNAL PROCESSING AND MODELING, 
    #%              John Wiley & Sons, 1996, Chapter 8
    #%   Author(s): R. Losada
    #%   Copyright 1988-2004 The MathWorks, Inc.
    #%   $Revision: 1.12.4.6 $  $Date: 2012/10/29 19:30:38 $
#     matcompat.error(nargchk(2., 2., nargin, 'struct'))
#     #% Check the input data type. Single precision is not supported.
#     #%try
#     #%    chkinputdatatype(x,p);
#     #%catch ME
#     #%    throwAsCaller(ME);
#     #%end
#     [mx, nx] = matcompat.size(x)
#     if isempty(x) or length(x)<p or matcompat.max(mx, nx) > 1.:
#         matcompat.error(message('signal:aryule:InvalidDimensions'))
#     elif isempty(p) or not p == np.round(p):
#         matcompat.error(message('signal:aryule:MustBeInteger'))
#         
#     
#     if issparse(x):
#         matcompat.error(message('signal:aryule:Sparse'))
#     
#     
#     R = plt.xcorr(x, p, 'biased')
#     [a, e, k] = levinson(R[int(p+1.)-1:], p)
#     return [a, e, k]
Beispiel #17
0
def create_all_psd():

    f = pylab.linspace(0, 1, 4096)
    pylab.clf()

    pylab.figure(figsize=(12, 8))

    #MA 15 order
    b, rho = spectrum.ma(data, 15, 30)
    psd = spectrum.arma2psd(B=b, rho=rho)
    newpsd = tools.cshift(psd,
                          len(psd) // 2)  # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd / max(newpsd)), label='MA 15')

    #ARMA 15 order
    a, b, rho = spectrum.arma_estimate(data, 15, 15, 30)
    psd = spectrum.arma2psd(A=a, B=b, rho=rho)
    newpsd = tools.cshift(psd,
                          len(psd) // 2)  # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd / max(newpsd)), label='ARMA 15,15')

    #yulewalker
    ar, P, c = spectrum.aryule(data, 15, norm='biased')
    psd = spectrum.arma2psd(A=ar, rho=P)
    newpsd = tools.cshift(psd,
                          len(psd) // 2)  # switch positive and negative freq

    pylab.plot(f,
               10 * pylab.log10(newpsd / max(newpsd)),
               label='YuleWalker 15')

    #burg method
    ar, P, k = spectrum.arburg(data, order=15)
    psd = spectrum.arma2psd(A=ar, rho=P)
    newpsd = tools.cshift(psd,
                          len(psd) // 2)  # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd / max(newpsd)), label='Burg 15')

    #covar method
    af, pf, ab, pb, pv = spectrum.arcovar_marple(data, 15)
    psd = spectrum.arma2psd(A=af, B=ab, rho=pf)
    newpsd = tools.cshift(psd,
                          len(psd) // 2)  # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd / max(newpsd)), label='covar 15')

    #modcovar method
    a, p, pv = spectrum.modcovar_marple(data, 15)
    psd = spectrum.arma2psd(A=a)
    newpsd = tools.cshift(psd,
                          len(psd) // 2)  # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd / max(newpsd)), label='modcovar 15')

    #correlogram
    psd = spectrum.CORRELOGRAMPSD(data, data, lag=15)
    newpsd = tools.cshift(psd,
                          len(psd) / 2)  # switch positive and negative freq
    pylab.plot(f,
               10 * pylab.log10(newpsd / max(newpsd)),
               label='correlogram 15')

    #minvar
    psd = spectrum.minvar(data, 15)
    #newpsd = tools.cshift(psd, len(psd)/2) # switch positive and negative freq
    pylab.plot(f, 10 * pylab.log10(newpsd / max(newpsd)), label='MINVAR 15')

    #music
    psd, db = spectrum.music(data, 15, 11)
    pylab.plot(f, 10 * pylab.log10(psd / max(psd)), '--', label='MUSIC 15')

    #ev music
    psd, db = spectrum.ev(data, 15, 11)
    pylab.plot(f, 10 * pylab.log10(psd / max(psd)), '--', label='EV 15')

    pylab.legend(loc='upper left', prop={'size': 10}, ncol=2)
    pylab.ylim([-80, 10])
    pylab.savefig('psd_all.png')
Beispiel #18
0
plt.title("Risp. impulsiva: 'h_a_calc', con attenuazione esponenziale")
plt.plot(t, -exp_win, 'r')
plt.plot(t,  exp_win, 'r')
plt.grid(True)
#plt.axis([0, max(t), -1, 1])

#=========================================================\
# 12) Modelli vari AR

#=================  ARYULE agorithm === (ECCEZIONALE *****) ==========
#     Modello AR(MA) di Yule-Walker: dalla risposta impulsiva
#     ricava un sistema a(z), questo modello ha 1 solo parametro: il n_zeri.
#
model_type = "ARYULE"
Ar_y_calc = np.zeros(N)
a, e, Ar_y_calc[0:N-1] = aryule(h_a_calc, N-1)      # equals the following 2 lines
### R = xcorr(h_a_calc, N,'biased');
### [a, e, Ar_y_calc] = levinson(R(N+1:end), N);    # levinson is a MEX compiled function
#====================================================================

#==========  AR Burg agorithm === (SPORCO RITORNA IL DOPPIO !! ! ) ====
#
#Ar_y_calc = np.zeros(N)
#a, e, Ar_y_calc = arburg(h_a_calc, N)
#Ar_y_calc       = Ar_y_calc / 2
### Ar_y_calc = Ar_y_calc(1,:)'; # returns a 2rows vect., 2nd row is a constant value!?
### Ar_y_calc = [Ar_y_calc; Ar_y_calc(N)]; Ar_y_calc = Ar_y_calc(2: N+1); # Shift left

#==========  Codice scritto ex novo: Collomb's C++ code, pp. 10-11 ====
#
# Burgs Method, algorithm and recursion. TERRIBILE,RITORNA IL DOPPIO !!!
 def fetureAR(self,ch):
     ar_coeffs, dnr, reflection_coeffs = spectrum.aryule(ch,ar_elements)
     return np.abs(ar_coeffs)
Beispiel #20
0
    def set_hyperparms(self):
        time = np.array(list(range(1, self.K + 1)))

        ## initialize arrays
        m = np.full([self.N, 1], np.nan)  # slope estimates
        s = np.full([self.N, 1], np.nan)  # paramater covariance estimates
        r = np.full([self.N, 1], np.nan)
        e = np.full([self.N, 1], np.nan)
        n = np.full([self.N, 1], np.nan)
        l = np.full([self.N, 1], np.nan)  # mean fit estimate
        y0 = np.full([self.N, 1], np.nan)

        for n in range(self.N):
            ## calculate the process parameters by using trend diff
            y = self.tg_data[n, :]
            mask = ~np.isnan(y)
            y, t = y[mask], time[mask]
            coeffs, cov = np.polyfit(t, y, 1, cov=True)
            m[n] = coeffs[0]
            s[n] = cov[0, 0]
            l[n] = coeffs[0] * time.mean() + coeffs[1]
            y0[n] = coeffs[1] - l[n]  # predicted mean - offset
            ## for residual between time series and fit, model as ar1 process ideally results in white noise
            a, b = spectrum.aryule(y - coeffs[0] * t - coeffs[1], 1)[:2]
            r[n] = -a
            e[n] = np.sqrt(b)

        ## ddof needs to be 1 for unbiased
        ## variance inflation parameters (to expand priors)
        var_infl, var_infl2, var0_infl = 5**2, 10**2, 1
        HP = {}
        # y0
        HP['eta_tilde_y0'] = np.nanmean(y0)  # mean of y0 prior
        HP['delta_tilde_y0_2'] = var0_infl * np.nanvar(
            y0, ddof=1)  # var of y0 prior

        # r
        HP['u_tilde_r'] = 0  # lower bound of r (uniform) prior
        HP['v_tilde_r'] = 1  # upper bound of r (uniform) prior

        # mu
        HP['eta_tilde_mu'] = np.nanmean(m)  # mean of mu (rate) prior
        HP['delta_tilde_mu_2'] = var_infl2 * np.nanvar(
            m, ddof=1)  # var of mu prior

        # nu
        HP['eta_tilde_nu'] = np.nanmean(l)  # mean of nu (mean pred) prior
        HP['delta_tilde_nu_2'] = var_infl * np.nanvar(
            l, ddof=1)  # var of nu prior

        # pi_2
        HP['lambda_tilde_pi_2'] = 0.5  # shape of pi_2 prior
        HP['nu_tilde_pi_2'] = 1 / 2 * np.nanvar(
            m, ddof=1)  # inverse scale of pi_2 prior

        # delta_2
        HP['lambda_tilde_delta_2'] = 0.5  # Shape of delta_2 prior
        HP['nu_tilde_delta_2'] = 0.5 * 1e-4  # Guess (1 cm)^2 error variance

        # sigma_2
        HP['lambda_tilde_sigma_2'] = 0.5  # Shape of sigma_2 prior
        HP['nu_tilde_sigma_2'] = 0.5 * np.nanmean(
            e**2)  # Inverse scale of sigma_2 prior

        # tau_2
        HP['lambda_tilde_tau_2'] = 0.5  # Shape of tau_2 prior
        HP['nu_tilde_tau_2'] = 0.5 * np.nanvar(
            l, ddof=1)  # Inverse scale of tau_2 prior

        # phi
        HP['eta_tilde_phi'] = -7  # "Mean" of phi prior
        HP['delta_tilde_phi_2'] = 5  # "Variance" of phi prior

        return HP
Beispiel #21
0
def aryule(x, p):
    """From MATLAB:
    %   A = ARYULE(X,ORDER) returns the polynomial A corresponding to the AR
    %   parametric signal model estimate of vector X using the Yule-Walker
    %   (autocorrelation) method.  ORDER is the model order of the AR system. 
    %   This method solves the Yule-Walker equations by means of the Levinson-
    %   Durbin recursion.
    %
    %   [A,E] = ARYULE(...) returns the final prediction error E (the variance
    %   estimate of the white noise input to the AR model).
    %
    %   [A,E,K] = ARYULE(...) returns the vector K of reflection coefficients.
    
    Using spectrum aryule:
    def aryule(X, order, norm='biased', allow_singularity=True):
        Compute AR coefficients using Yule-Walker method
        
        :param X: Array of complex data values, X(1) to X(N)
        :param int order: Order of autoregressive process to be fitted (integer)
        :param str norm: Use a biased or unbiased correlation.
        :param bool allow_singularity: 
        
        :return:
        * AR coefficients (complex)
        * variance of white noise (Real)
        * reflection coefficients for use in lattice filter 
    """
    [A, E, K] = spectrum.aryule(x, p)
    A = np.hstack((1, A))  # MATLAB adds the first "1.0"
    return A, E, K

    # Local Variables: a, e, k, nx, p, R, x, mx
    # Function calls: aryule, nargchk, min, issparse, nargin, length, isempty, error, levinson, message, xcorr, round, size
    #%ARYULE   AR parameter estimation via Yule-Walker method.
    #%   A = ARYULE(X,ORDER) returns the polynomial A corresponding to the AR
    #%   parametric signal model estimate of vector X using the Yule-Walker
    #%   (autocorrelation) method.  ORDER is the model order of the AR system.
    #%   This method solves the Yule-Walker equations by means of the Levinson-
    #%   Durbin recursion.
    #%
    #%   [A,E] = ARYULE(...) returns the final prediction error E (the variance
    #%   estimate of the white noise input to the AR model).
    #%
    #%   [A,E,K] = ARYULE(...) returns the vector K of reflection coefficients.
    #%
    #%   % Example:
    #%   %   Estimate model order using decay of reflection coefficients.
    #%
    #%   rng default;
    #%   y=filter(1,[1 -0.75 0.5],0.2*randn(1024,1));
    #%
    #%   % Create AR(2) process
    #%   [ar_coeffs,NoiseVariance,reflect_coeffs]=aryule(y,10);
    #%
    #%   % Fit AR(10) model
    #%   stem(reflect_coeffs); axis([-0.05 10.5 -1 1]);
    #%   title('Reflection Coefficients by Lag'); xlabel('Lag');
    #%   ylabel('Reflection Coefficent');
    #%
    #%   See also PYULEAR, ARMCOV, ARBURG, ARCOV, LPC, PRONY.
    #%   Ref: S. Orfanidis, OPTIMUM SIGNAL PROCESSING, 2nd Ed.
    #%              Macmillan, 1988, Chapter 5
    #%        M. Hayes, STATISTICAL DIGITAL SIGNAL PROCESSING AND MODELING,
    #%              John Wiley & Sons, 1996, Chapter 8
    #%   Author(s): R. Losada
    #%   Copyright 1988-2004 The MathWorks, Inc.
    #%   $Revision: 1.12.4.6 $  $Date: 2012/10/29 19:30:38 $


#     matcompat.error(nargchk(2., 2., nargin, 'struct'))
#     #% Check the input data type. Single precision is not supported.
#     #%try
#     #%    chkinputdatatype(x,p);
#     #%catch ME
#     #%    throwAsCaller(ME);
#     #%end
#     [mx, nx] = matcompat.size(x)
#     if isempty(x) or length(x)<p or matcompat.max(mx, nx) > 1.:
#         matcompat.error(message('signal:aryule:InvalidDimensions'))
#     elif isempty(p) or not p == np.round(p):
#         matcompat.error(message('signal:aryule:MustBeInteger'))
#
#
#     if issparse(x):
#         matcompat.error(message('signal:aryule:Sparse'))
#
#
#     R = plt.xcorr(x, p, 'biased')
#     [a, e, k] = levinson(R[int(p+1.)-1:], p)
#     return [a, e, k]
Beispiel #22
0
 def calc_for_ch(self, ch):
     ar_coeffs, dnr, reflection_coeffs = spectrum.aryule(ch, self.order)
     return np.abs(ar_coeffs)
 def calc_for_ch(self, ch):
     ar_coeffs, dnr, reflection_coeffs = spectrum.aryule(ch, self.order)
     return np.abs(ar_coeffs)