def polymul(a1, a2): """ Returns product of two polynomials represented as sequences. The input arrays specify the polynomial terms in turn with a length equal to the polynomial degree plus 1. Parameters ---------- a1 : {array_like, poly1d} First multiplier polynomial. a2 : {array_like, poly1d} Second multiplier polynomial. Returns ------- out : {ndarray, poly1d} Product of inputs. See Also -------- poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1, a2 = poly1d(a1), poly1d(a2) val = NX.convolve(a1, a2) if truepoly: val = poly1d(val) return val
def polymul(a1, a2): """ Returns product of two polynomials represented as sequences. The input arrays specify the polynomial terms in turn with a length equal to the polynomial degree plus 1. Parameters ---------- a1 : {array_like, poly1d} First multiplier polynomial. a2 : {array_like, poly1d} Second multiplier polynomial. Returns ------- out : {ndarray, poly1d} Product of inputs. See Also -------- poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1,a2 = poly1d(a1),poly1d(a2) val = NX.convolve(a1, a2) if truepoly: val = poly1d(val) return val
def polymul(a1, a2): """ Find the product of two polynomials. .. note:: This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in `numpy.polynomial` is preferred. A summary of the differences can be found in the :doc:`transition guide </reference/routines.polynomials>`. Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- a1, a2 : array_like or poly1d object Input polynomials. Returns ------- out : ndarray or poly1d object The polynomial resulting from the multiplication of the inputs. If either inputs is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree. See Also -------- poly1d : A one-dimensional polynomial class. poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval convolve : Array convolution. Same output as polymul, but has parameter for overlap mode. Examples -------- >>> np.polymul([1, 2, 3], [9, 5, 1]) array([ 9, 23, 38, 17, 3]) Using poly1d objects: >>> p1 = np.poly1d([1, 2, 3]) >>> p2 = np.poly1d([9, 5, 1]) >>> print(p1) 2 1 x + 2 x + 3 >>> print(p2) 2 9 x + 5 x + 1 >>> print(np.polymul(p1, p2)) 4 3 2 9 x + 23 x + 38 x + 17 x + 3 """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1, a2 = poly1d(a1), poly1d(a2) val = NX.convolve(a1, a2) if truepoly: val = poly1d(val) return val
def polymul(a1, a2): """Multiplies two polynomials represented as sequences. """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1,a2 = poly1d(a1),poly1d(a2) val = NX.convolve(a1, a2) if truepoly: val = poly1d(val) return val
def polymul(a1, a2): """ Find the product of two polynomials. Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- a1, a2 : array_like or poly1d object Input polynomials. Returns ------- out : ndarray or poly1d object The polynomial resulting from the multiplication of the inputs. If either inputs is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree. See Also -------- poly1d : A one-dimensional polynomial class. poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval convolve : Array convolution. Same output as polymul, but has parameter for overlap mode. Examples -------- >>> np.polymul([1, 2, 3], [9, 5, 1]) array([ 9, 23, 38, 17, 3]) Using poly1d objects: >>> p1 = np.poly1d([1, 2, 3]) >>> p2 = np.poly1d([9, 5, 1]) >>> print p1 2 1 x + 2 x + 3 >>> print p2 2 9 x + 5 x + 1 >>> print np.polymul(p1, p2) 4 3 2 9 x + 23 x + 38 x + 17 x + 3 """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1, a2 = poly1d(a1), poly1d(a2) val = NX.convolve(a1, a2) if truepoly: val = poly1d(val) return val
def polymul(a1, a2): """ Find the product of two polynomials. Finds the polynomial resulting from the multiplication of the two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- a1, a2 : array_like or poly1d object Input polynomials. Returns ------- out : ndarray or poly1d object The polynomial resulting from the multiplication of the inputs. If either inputs is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree. See Also -------- poly1d : A one-dimensional polynomial class. poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval convolve : Array convolution. Same output as polymul, but has parameter for overlap mode. Examples -------- >>> np.polymul([1, 2, 3], [9, 5, 1]) array([ 9, 23, 38, 17, 3]) Using poly1d objects: >>> p1 = np.poly1d([1, 2, 3]) >>> p2 = np.poly1d([9, 5, 1]) >>> print(p1) 2 1 x + 2 x + 3 >>> print(p2) 2 9 x + 5 x + 1 >>> print(np.polymul(p1, p2)) 4 3 2 9 x + 23 x + 38 x + 17 x + 3 """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1, a2 = poly1d(a1), poly1d(a2) val = NX.convolve(a1, a2) if truepoly: val = poly1d(val) return val
def estimate_beta_band(session,area,bw=8,epoch=None,doplot=False): ''' return betapeak-0.5*bw,betapeak+0.5*bw ''' print 'THIS IS NOT THE ONE YOU WANT TO USE' print 'IT IS EXPERIMENTAL COHERENCE BASED IDENTIFICATION OF BETA' assert 0 if epoch is None: epoch = (6,-1000,3000) allco = [] if not area is None: chs = get_good_channels(session,area)[:2] for a in chs: for b in chs: if a==b: continue for tr in get_good_trials(session): x = get_filtered_lfp(session,area,a,tr,epoch,None,300) y = get_filtered_lfp(session,area,b,tr,epoch,None,300) co,fr = cohere(x,y,Fs=1000,NFFT=256) allco.append(co) else: for area in areas: chs = get_good_channels(session,area)[:2] for a in chs: for b in chs: if a==b: continue for tr in get_good_trials(session): x = get_filtered_lfp(session,area,a,tr,epoch,None,300) y = get_filtered_lfp(session,area,b,tr,epoch,None,300) co,fr = cohere(x,y,Fs=1000,NFFT=256) allco.append(co) allco = array(allco) m = mean(allco,0) sem = std(allco,0)/sqrt(shape(allco)[0]) # temporary in lieu of multitaper smooth = ceil(float(bw)/(diff(fr)[0])) smoothed = convolve(m,ones(smooth)/smooth,'same') use = (fr<=56)&(fr>=5) betafr = (fr<=30-0.5*bw)&(fr>=15+0.5*bw) betapeak = fr[betafr][argmax(smoothed[betafr])] if doplot: clf() plot(fr[use],m[use],lw=2,color='k') plot(fr[use],smoothed[use],lw=1,color='r') plot(fr[use],(m+sem)[use],lw=1,color='k') plot(fr[use],(m-sem)[use],lw=1,color='k') positivey() xlim(*rangeover(fr[use])) shade([[betapeak-0.5*bw],[betapeak+0.5*bw]]) draw() return betapeak-0.5*bw,betapeak+0.5*bw
def poly(seq_of_zeros): """ Return a sequence representing a polynomial given a sequence of roots. If the input is a matrix, return the characteristic polynomial. Example: >>> b = roots([1,3,1,5,6]) >>> poly(b) array([ 1., 3., 1., 5., 6.]) """ seq_of_zeros = atleast_1d(seq_of_zeros) sh = seq_of_zeros.shape if len(sh) == 2 and sh[0] == sh[1]: seq_of_zeros = _eigvals(seq_of_zeros) elif len(sh) ==1: pass else: raise ValueError, "input must be 1d or square 2d array." if len(seq_of_zeros) == 0: return 1.0 a = [1] for k in range(len(seq_of_zeros)): a = NX.convolve(a, [1, -seq_of_zeros[k]], mode='full') if issubclass(a.dtype.type, NX.complexfloating): # if complex roots are all complex conjugates, the roots are real. roots = NX.asarray(seq_of_zeros, complex) pos_roots = sort_complex(NX.compress(roots.imag > 0, roots)) neg_roots = NX.conjugate(sort_complex( NX.compress(roots.imag < 0,roots))) if (len(pos_roots) == len(neg_roots) and NX.alltrue(neg_roots == pos_roots)): a = a.real.copy() return a
def poly(seq_of_zeros): """ Find the coefficients of a polynomial with the given sequence of roots. Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square matrix (or array, which will be treated as a matrix) can also be given, in which case the coefficients of the characteristic polynomial of the matrix are returned. Parameters ---------- seq_of_zeros : array_like, shape (N,) or (N, N) A sequence of polynomial roots, or a square array or matrix object. Returns ------- c : ndarray 1D array of polynomial coefficients from highest to lowest degree: ``c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N]`` where c[0] always equals 1. Raises ------ ValueError If input is the wrong shape (the input must be a 1-D or square 2-D array). See Also -------- polyval : Evaluate a polynomial at a point. roots : Return the roots of a polynomial. polyfit : Least squares polynomial fit. poly1d : A one-dimensional polynomial class. Notes ----- Specifying the roots of a polynomial still leaves one degree of freedom, typically represented by an undetermined leading coefficient. [1]_ In the case of this function, that coefficient - the first one in the returned array - is always taken as one. (If for some reason you have one other point, the only automatic way presently to leverage that information is to use ``polyfit``.) The characteristic polynomial, :math:`p_a(t)`, of an `n`-by-`n` matrix **A** is given by :math:`p_a(t) = \\mathrm{det}(t\\, \\mathbf{I} - \\mathbf{A})`, where **I** is the `n`-by-`n` identity matrix. [2]_ References ---------- .. [1] M. Sullivan and M. Sullivan, III, "Algebra and Trignometry, Enhanced With Graphing Utilities," Prentice-Hall, pg. 318, 1996. .. [2] G. Strang, "Linear Algebra and Its Applications, 2nd Edition," Academic Press, pg. 182, 1980. Examples -------- Given a sequence of a polynomial's zeros: >>> np.poly((0, 0, 0)) # Multiple root example array([1, 0, 0, 0]) The line above represents z**3 + 0*z**2 + 0*z + 0. >>> np.poly((-1./2, 0, 1./2)) array([ 1. , 0. , -0.25, 0. ]) The line above represents z**3 - z/4 >>> np.poly((np.random.random(1.)[0], 0, np.random.random(1.)[0])) array([ 1. , -0.77086955, 0.08618131, 0. ]) #random Given a square array object: >>> P = np.array([[0, 1./3], [-1./2, 0]]) >>> np.poly(P) array([ 1. , 0. , 0.16666667]) Or a square matrix object: >>> np.poly(np.matrix(P)) array([ 1. , 0. , 0.16666667]) Note how in all cases the leading coefficient is always 1. """ seq_of_zeros = atleast_1d(seq_of_zeros) sh = seq_of_zeros.shape if len(sh) == 2 and sh[0] == sh[1] and sh[0] != 0: seq_of_zeros = eigvals(seq_of_zeros) elif len(sh) == 1: dt = seq_of_zeros.dtype # Let object arrays slip through, e.g. for arbitrary precision if dt != object: seq_of_zeros = seq_of_zeros.astype(mintypecode(dt.char)) else: raise ValueError("input must be 1d or non-empty square 2d array.") if len(seq_of_zeros) == 0: return 1.0 dt = seq_of_zeros.dtype a = ones((1, ), dtype=dt) for k in range(len(seq_of_zeros)): a = NX.convolve(a, array([1, -seq_of_zeros[k]], dtype=dt), mode='full') if issubclass(a.dtype.type, NX.complexfloating): # if complex roots are all complex conjugates, the roots are real. roots = NX.asarray(seq_of_zeros, complex) pos_roots = sort_complex(NX.compress(roots.imag > 0, roots)) neg_roots = NX.conjugate( sort_complex(NX.compress(roots.imag < 0, roots))) if (len(pos_roots) == len(neg_roots) and NX.alltrue(neg_roots == pos_roots)): a = a.real.copy() return a
def poly(seq_of_zeros): """ Find the coefficients of a polynomial with the given sequence of roots. Returns the coefficients of the polynomial whose leading coefficient is one for the given sequence of zeros (multiple roots must be included in the sequence as many times as their multiplicity; see Examples). A square matrix (or array, which will be treated as a matrix) can also be given, in which case the coefficients of the characteristic polynomial of the matrix are returned. Parameters ---------- seq_of_zeros : array_like, shape (N,) or (N, N) A sequence of polynomial roots, or a square array or matrix object. Returns ------- c : ndarray 1D array of polynomial coefficients from highest to lowest degree: ``c[0] * x**(N) + c[1] * x**(N-1) + ... + c[N-1] * x + c[N]`` where c[0] always equals 1. Raises ------ ValueError If input is the wrong shape (the input must be a 1-D or square 2-D array). See Also -------- polyval : Evaluate a polynomial at a point. roots : Return the roots of a polynomial. polyfit : Least squares polynomial fit. poly1d : A one-dimensional polynomial class. Notes ----- Specifying the roots of a polynomial still leaves one degree of freedom, typically represented by an undetermined leading coefficient. [1]_ In the case of this function, that coefficient - the first one in the returned array - is always taken as one. (If for some reason you have one other point, the only automatic way presently to leverage that information is to use ``polyfit``.) The characteristic polynomial, :math:`p_a(t)`, of an `n`-by-`n` matrix **A** is given by :math:`p_a(t) = \\mathrm{det}(t\\, \\mathbf{I} - \\mathbf{A})`, where **I** is the `n`-by-`n` identity matrix. [2]_ References ---------- .. [1] M. Sullivan and M. Sullivan, III, "Algebra and Trignometry, Enhanced With Graphing Utilities," Prentice-Hall, pg. 318, 1996. .. [2] G. Strang, "Linear Algebra and Its Applications, 2nd Edition," Academic Press, pg. 182, 1980. Examples -------- Given a sequence of a polynomial's zeros: >>> np.poly((0, 0, 0)) # Multiple root example array([1, 0, 0, 0]) The line above represents z**3 + 0*z**2 + 0*z + 0. >>> np.poly((-1./2, 0, 1./2)) array([ 1. , 0. , -0.25, 0. ]) The line above represents z**3 - z/4 >>> np.poly((np.random.random(1.)[0], 0, np.random.random(1.)[0])) array([ 1. , -0.77086955, 0.08618131, 0. ]) #random Given a square array object: >>> P = np.array([[0, 1./3], [-1./2, 0]]) >>> np.poly(P) array([ 1. , 0. , 0.16666667]) Or a square matrix object: >>> np.poly(np.matrix(P)) array([ 1. , 0. , 0.16666667]) Note how in all cases the leading coefficient is always 1. """ seq_of_zeros = atleast_1d(seq_of_zeros) sh = seq_of_zeros.shape if len(sh) == 2 and sh[0] == sh[1] and sh[0] != 0: seq_of_zeros = eigvals(seq_of_zeros) elif len(sh) == 1: pass else: raise ValueError("input must be 1d or square 2d array.") if len(seq_of_zeros) == 0: return 1.0 a = [1] for k in range(len(seq_of_zeros)): a = NX.convolve(a, [1, -seq_of_zeros[k]], mode='full') if issubclass(a.dtype.type, NX.complexfloating): # if complex roots are all complex conjugates, the roots are real. roots = NX.asarray(seq_of_zeros, complex) pos_roots = sort_complex(NX.compress(roots.imag > 0, roots)) neg_roots = NX.conjugate(sort_complex( NX.compress(roots.imag < 0,roots))) if (len(pos_roots) == len(neg_roots) and NX.alltrue(neg_roots == pos_roots)): a = a.real.copy() return a
def poly(seq_of_zeros): """ Return polynomial coefficients given a sequence of roots. Calculate the coefficients of a polynomial given the zeros of the polynomial. If a square matrix is given, then the coefficients for characteristic equation of the matrix, defined by :math:`\\mathrm{det}(\\mathbf{A} - \\lambda \\mathbf{I})`, are returned. Parameters ---------- seq_of_zeros : ndarray A sequence of polynomial roots or a square matrix. Returns ------- coefs : ndarray A sequence of polynomial coefficients representing the polynomial :math:`\\mathrm{coefs}[0] x^{n-1} + \\mathrm{coefs}[1] x^{n-2} + ... + \\mathrm{coefs}[2] x + \\mathrm{coefs}[n]` See Also -------- numpy.poly1d : A one-dimensional polynomial class. numpy.roots : Return the roots of the polynomial coefficients in p numpy.polyfit : Least squares polynomial fit Examples -------- Given a sequence of polynomial zeros, >>> b = np.roots([1, 3, 1, 5, 6]) >>> np.poly(b) array([ 1., 3., 1., 5., 6.]) Given a square matrix, >>> P = np.array([[19, 3], [-2, 26]]) >>> np.poly(P) array([ 1., -45., 500.]) """ seq_of_zeros = atleast_1d(seq_of_zeros) sh = seq_of_zeros.shape if len(sh) == 2 and sh[0] == sh[1]: seq_of_zeros = eigvals(seq_of_zeros) elif len(sh) ==1: pass else: raise ValueError, "input must be 1d or square 2d array." if len(seq_of_zeros) == 0: return 1.0 a = [1] for k in range(len(seq_of_zeros)): a = NX.convolve(a, [1, -seq_of_zeros[k]], mode='full') if issubclass(a.dtype.type, NX.complexfloating): # if complex roots are all complex conjugates, the roots are real. roots = NX.asarray(seq_of_zeros, complex) pos_roots = sort_complex(NX.compress(roots.imag > 0, roots)) neg_roots = NX.conjugate(sort_complex( NX.compress(roots.imag < 0,roots))) if (len(pos_roots) == len(neg_roots) and NX.alltrue(neg_roots == pos_roots)): a = a.real.copy() return a
def poly(seq_of_zeros): """ Return polynomial coefficients given a sequence of roots. Calculate the coefficients of a polynomial given the zeros of the polynomial. If a square matrix is given, then the coefficients for characteristic equation of the matrix, defined by :math:`\\mathrm{det}(\\mathbf{A} - \\lambda \\mathbf{I})`, are returned. Parameters ---------- seq_of_zeros : ndarray A sequence of polynomial roots or a square matrix. Returns ------- coefs : ndarray A sequence of polynomial coefficients representing the polynomial :math:`\\mathrm{coefs}[0] x^{n-1} + \\mathrm{coefs}[1] x^{n-2} + ... + \\mathrm{coefs}[2] x + \\mathrm{coefs}[n]` See Also -------- numpy.poly1d : A one-dimensional polynomial class. numpy.roots : Return the roots of the polynomial coefficients in p numpy.polyfit : Least squares polynomial fit Examples -------- Given a sequence of polynomial zeros, >>> b = np.roots([1, 3, 1, 5, 6]) >>> np.poly(b) array([ 1., 3., 1., 5., 6.]) Given a square matrix, >>> P = np.array([[19, 3], [-2, 26]]) >>> np.poly(P) array([ 1., -45., 500.]) """ seq_of_zeros = atleast_1d(seq_of_zeros) sh = seq_of_zeros.shape if len(sh) == 2 and sh[0] == sh[1]: seq_of_zeros = eigvals(seq_of_zeros) elif len(sh) == 1: pass else: raise ValueError, "input must be 1d or square 2d array." if len(seq_of_zeros) == 0: return 1.0 a = [1] for k in range(len(seq_of_zeros)): a = NX.convolve(a, [1, -seq_of_zeros[k]], mode='full') if issubclass(a.dtype.type, NX.complexfloating): # if complex roots are all complex conjugates, the roots are real. roots = NX.asarray(seq_of_zeros, complex) pos_roots = sort_complex(NX.compress(roots.imag > 0, roots)) neg_roots = NX.conjugate( sort_complex(NX.compress(roots.imag < 0, roots))) if (len(pos_roots) == len(neg_roots) and NX.alltrue(neg_roots == pos_roots)): a = a.real.copy() return a
def get_high_beta_events(session,area,channel,epoch, MINLEN = 40, # ms BOXLEN = 50, # ms THSCALE = 1.5, # sigma (standard deviations) lowf = 10.0, # Hz highf = 45.0, # Hz pad = 200, # ms clip = True, audit = False ): ''' get_high_beta_events(session,area,channel,epoch) will identify periods of elevated beta-frequency power for the given channel. Thresholds are selected per-channel based on all available trials. The entire trial time is used when estimating the average beta power. To avoid recomputing, we extract beta events for all trials at once. By default events that extend past the edge of the specified epoch will be clipped. Passing clip=False will discard these events. returns the event threshold, and a list of event start and stop times relative to session time (not per-trial or epoch time) passing audit=True will enable previewing each trial and the isolated beta events. >>> thr,events = get_high_beta_events('SPK120925','PMd',50,(6,-1000,0)) ''' # get LFP data signal = get_raw_lfp_session(session,area,channel) # esimate threshold for beta events beta_trials = [get_filtered_lfp(session,area,channel,t,(6,-1000,0),lowf,highf) for t in get_good_trials(session)] threshold = np.std(beta_trials)*THSCALE print 'threshold=',threshold N = len(signal) event,start,stop = epoch all_events = [] all_high_beta_times = [] for trial in get_good_trials(session): evt = get_trial_event(session,area,trial,event) trialstart = get_trial_event(session,area,trial,4) epochstart = evt + start + trialstart epochstop = evt + stop + trialstart tstart = max(0,epochstart-pad) tstop = min(N,epochstop +pad) filtered = bandfilter(signal[tstart:tstop],lowf,highf) envelope = abs(hilbert(filtered)) smoothed = convolve(envelope,ones(BOXLEN)/float(BOXLEN),'same') E = array(get_edges(smoothed>threshold))+tstart E = E[:,(diff(E,1,0)[0]>=MINLEN) & (E[0,:]<epochstop ) & (E[1,:]>epochstart)] if audit: print E if clip: E[0,:] = np.maximum(E[0,:],epochstart) E[1,:] = np.minimum(E[1,:],epochstop ) else: E = E[:,(E[1,:]<=epochstop)&(E[0,:]>=epochstart)] if audit: clf() axvspan(epochstart,epochstop,color=(0,0,0,0.25)) plot(arange(tstart,tstop),filtered,lw=0.7,color='k') plot(arange(tstart,tstop),envelope,lw=0.7,color='r') plot(arange(tstart,tstop),smoothed,lw=0.7,color='b') ylim(-80,80) for a,b in E.T: axvspan(a,b,color=(1,0,0,0.5)) axhline(threshold,color='k',lw=1.5) xlim(tstart,tstop) draw() wait() all_events.extend(E.T) assert all(diff(E,0,1)>=MINLEN) return threshold, all_events