#NEWLINE# def varfilter( x , a ) : #NEWLINE# #INDENT# "apply an autoregressive filter to a series x\n\n    Warning: I just found out that convolve doesn't work as I\n       thought, this likely doesn't work correctly for\n       nvars>3\n\n\n    x can be 2d, a can be 1d, 2d, or 3d\n\n    Parameters\n    ----------\n    x : array_like\n        data array, 1d or 2d, if 2d then observations in rows\n    a : array_like\n        autoregressive filter coefficients, ar lag polynomial\n        see Notes\n\n    Returns\n    -------\n    y : ndarray, 2d\n        filtered array, number of columns determined by x and a\n\n    Notes\n    -----\n\n    In general form this uses the linear filter ::\n\n        y = a(L)x\n\n    where\n    x : nobs, nvars\n    a : nlags, nvars, npoly\n\n    Depending on the shape and dimension of a this uses different\n    Lag polynomial arrays\n\n    case 1 : a is 1d or (nlags,1)\n        one lag polynomial is applied to all variables (columns of x)\n    case 2 : a is 2d, (nlags, nvars)\n        each series is independently filtered with its own\n        lag polynomial, uses loop over nvar\n    case 3 : a is 3d, (nlags, nvars, npoly)\n        the ith column of the output array is given by the linear filter\n        defined by the 2d array a[:,:,i], i.e. ::\n\n            y[:,i] = a(.,.,i)(L) * x\n            y[t,i] = sum_p sum_j a(p,j,i)*x(t-p,j)\n                     for p = 0,...nlags-1, j = 0,...nvars-1,\n                     for all t >= nlags\n\n\n    Note: maybe convert to axis=1, Not\n\n    TODO: initial conditions\n\n    " #NEWLINE# x = np . asarray ( x ) #NEWLINE# a = np . asarray ( a ) #NEWLINE# if ( x . ndim == 1 ) : #NEWLINE# #INDENT# x = x [ : , None ] #NEWLINE# #UNINDENT# if ( x . ndim > 2 ) : #NEWLINE# #INDENT# raise ValueError ( 'x array has to be 1d or 2d' ) #NEWLINE# #UNINDENT# nvar = x . shape [ 1 ] #NEWLINE# nlags = a . shape [ 0 ] #NEWLINE# ntrim = ( nlags // 2 ) #NEWLINE# if ( a . ndim == 1 ) : #NEWLINE# #INDENT# return signal . convolve ( x , a [ : , None ] , mode = 'valid' ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if ( a . ndim == 2 ) : #NEWLINE# #INDENT# if ( min ( a . shape ) == 1 ) : #NEWLINE# #INDENT# return signal . convolve ( x , a , mode = 'valid' ) #NEWLINE# #UNINDENT# result = np . zeros ( ( ( ( x . shape [ 0 ] - nlags ) + 1 ) , nvar ) ) #NEWLINE# for i in range ( nvar ) : #NEWLINE# #INDENT# result [ : , i ] = signal . convolve ( x [ : , i ] , a [ : , i ] , mode = 'valid' ) #NEWLINE# #UNINDENT# return result #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if ( a . ndim == 3 ) : #NEWLINE# #INDENT# yf = signal . convolve ( x [ : , : , None ] , a ) #NEWLINE# yvalid = yf [ ntrim : ( - ntrim ) , ( yf . shape [ 1 ] // 2 ) , : ] #NEWLINE# return yvalid