예제 #1
0
    def _get_handles(self, handles, texts):
        HEIGHT = self._approx_text_height()

        ret = []  # the returned legend lines

        for handle, label in zip(handles, texts):
            x, y = label.get_position()
            x -= self.handlelen + self.handletextsep
            if isinstance(handle, Line2D):
                ydata = (y - HEIGHT / 2) * ones(self._xdata.shape, Float)
                legline = Line2D(self._xdata, ydata)
                legline.update_from(handle)
                self._set_artist_props(legline)  # after update
                legline.set_clip_box(None)
                legline.set_markersize(self.markerscale *
                                       legline.get_markersize())

                ret.append(legline)
            elif isinstance(handle, Patch):

                p = Rectangle(
                    xy=(min(self._xdata), y - 3 / 4 * HEIGHT),
                    width=self.handlelen,
                    height=HEIGHT / 2,
                )
                p.update_from(handle)
                self._set_artist_props(p)
                p.set_clip_box(None)
                ret.append(p)
            elif isinstance(handle, LineCollection):
                ydata = (y - HEIGHT / 2) * ones(self._xdata.shape, Float)
                legline = Line2D(self._xdata, ydata)
                self._set_artist_props(legline)
                legline.set_clip_box(None)
                lw = handle.get_linewidth()[0]
                dashes = handle.get_dashes()
                color = handle.get_colors()[0]
                legline.set_color(color)
                legline.set_linewidth(lw)
                legline.set_dashes(dashes)
                ret.append(legline)

            elif isinstance(handle, RegularPolyCollection):

                p = Rectangle(
                    xy=(min(self._xdata), y - 3 / 4 * HEIGHT),
                    width=self.handlelen,
                    height=HEIGHT / 2,
                )
                p.set_facecolor(handle._facecolors[0])
                if handle._edgecolors != 'None':
                    p.set_edgecolor(handle._edgecolors[0])
                self._set_artist_props(p)
                p.set_clip_box(None)
                ret.append(p)

            else:
                ret.append(None)

        return ret
예제 #2
0
파일: lines.py 프로젝트: jtomase/matplotlib
    def _get_plottable(self):
        # If log scale is set, only pos data will be returned

        x, y = self._x, self._y

        try: logx = self._transform.get_funcx().get_type()==LOG10
        except RuntimeError: logx = False  # non-separable

        try: logy = self._transform.get_funcy().get_type()==LOG10
        except RuntimeError: logy = False  # non-separable

        if not logx and not logy:
            return x, y

        if self._logcache is not None:
            waslogx, waslogy, xcache, ycache = self._logcache
            if logx==waslogx and waslogy==logy:
                return xcache, ycache

        Nx = len(x)
        Ny = len(y)

        if logx: indx = greater(x, 0)
        else:    indx = ones(len(x))

        if logy: indy = greater(y, 0)
        else:    indy = ones(len(y))

        ind = nonzero(logical_and(indx, indy))
        x = take(x, ind)
        y = take(y, ind)

        self._logcache = logx, logy, x, y
        return x, y
예제 #3
0
파일: lines.py 프로젝트: jtomase/matplotlib
    def _update_x_y_logcache(self):
        # check cache
        need_update = False
        try:
            for key, var_id in self._cache_inputs.iteritems():
                if (id(getattr(self, key)) != var_id):
                    need_update = True
                    break
        except:
            need_update = True

        if (not need_update):
            return

        # update cache
        for key in self._cache_inputs.keys():
            try:
                self._cache_inputs[key] = id(getattr(self, key))
            except:
                pass

        # make sure that result values exist and release
        # previous values
        self._cached__x = None
        self._cached__y = None
        self._cached__segments = None
        self._cached__logcache = None

        if (self.is_unitsmgr_set()):
            unitsmgr = self.get_unitsmgr()
            x, y = unitsmgr._convert_units((self._x_orig, self._xunits),
                                           (self._y_orig, self._yunits))
        else:
            x, y = (self._x_orig, self._y_orig)

        x = ma.ravel(x)
        y = ma.ravel(y)
        if len(x) == 1 and len(y) > 1:
            x = x * ones(y.shape, Float)
        if len(y) == 1 and len(x) > 1:
            y = y * ones(x.shape, Float)

        if len(x) != len(y):
            raise RuntimeError('xdata and ydata must be the same length')

        mx = ma.getmask(x)
        my = ma.getmask(y)
        mask = ma.mask_or(mx, my)
        if mask is not ma.nomask:
            x = ma.masked_array(x, mask=mask).compressed()
            y = ma.masked_array(y, mask=mask).compressed()
            self._cached__segments = unmasked_index_ranges(mask)
        else:
            self._cached__segments = None

        self._cached__x = asarray(x, Float)
        self._cached__y = asarray(y, Float)

        self._cached__logcache = None
예제 #4
0
    def _update_x_y_logcache(self):
        # check cache
        need_update = False
        try:
            for key, var_id in self._cache_inputs.iteritems():
                if id(getattr(self, key)) != var_id:
                    need_update = True
                    break
        except:
            need_update = True

        if not need_update:
            return

        # update cache
        for key in self._cache_inputs.keys():
            try:
                self._cache_inputs[key] = id(getattr(self, key))
            except:
                pass

        # make sure that result values exist and release
        # previous values
        self._cached__x = None
        self._cached__y = None
        self._cached__segments = None
        self._cached__logcache = None

        if self.is_unitsmgr_set():
            unitsmgr = self.get_unitsmgr()
            x, y = unitsmgr._convert_units((self._x_orig, self._xunits), (self._y_orig, self._yunits))
        else:
            x, y = (self._x_orig, self._y_orig)

        x = ma.ravel(x)
        y = ma.ravel(y)
        if len(x) == 1 and len(y) > 1:
            x = x * ones(y.shape, Float)
        if len(y) == 1 and len(x) > 1:
            y = y * ones(x.shape, Float)

        if len(x) != len(y):
            raise RuntimeError("xdata and ydata must be the same length")

        mx = ma.getmask(x)
        my = ma.getmask(y)
        mask = ma.mask_or(mx, my)
        if mask is not ma.nomask:
            x = ma.masked_array(x, mask=mask).compressed()
            y = ma.masked_array(y, mask=mask).compressed()
            self._cached__segments = unmasked_index_ranges(mask)
        else:
            self._cached__segments = None

        self._cached__x = asarray(x, Float)
        self._cached__y = asarray(y, Float)

        self._cached__logcache = None
예제 #5
0
def vec_pad_ones(xs, ys, zs):
    try:
        try:
            vec = nx.array([xs, ys, zs, nx.ones(xs.shape)])
        except (AttributeError, TypeError):
            vec = nx.array([xs, ys, zs, nx.ones((len(xs)))])
    except TypeError:
        vec = nx.array([xs, ys, zs, 1])
    return vec
예제 #6
0
 def _draw_steps(self, renderer, gc, xt, yt):
     siz=len(xt)
     if siz<2: return
     xt2=ones((2*siz,), xt.typecode())
     xt2[0:-1:2], xt2[1:-1:2], xt2[-1]=xt, xt[1:], xt[-1]
     yt2=ones((2*siz,), yt.typecode())
     yt2[0:-1:2], yt2[1::2]=yt, yt
     gc.set_linestyle('solid')
     gc.set_capstyle('projecting')
     renderer.draw_lines(gc, xt2, yt2)    
예제 #7
0
파일: lines.py 프로젝트: jtomase/matplotlib
 def _draw_steps(self, renderer, gc, xt, yt):
     siz = len(xt)
     if siz < 2: return
     xt2 = ones((2 * siz, ), xt.typecode())
     xt2[0:-1:2], xt2[1:-1:2], xt2[-1] = xt, xt[1:], xt[-1]
     yt2 = ones((2 * siz, ), yt.typecode())
     yt2[0:-1:2], yt2[1::2] = yt, yt
     gc.set_linestyle('solid')
     gc.set_capstyle('projecting')
     renderer.draw_lines(gc, xt2, yt2)
예제 #8
0
파일: legend.py 프로젝트: pv/matplotlib-cvs
    def _get_handles(self, handles, texts):
        HEIGHT = self._approx_text_height()

        ret = []   # the returned legend lines

        for handle, label in zip(handles, texts):
            x, y = label.get_position()
            x -= self.handlelen + self.handletextsep
            if isinstance(handle, Line2D):
                ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float)
                legline = Line2D(self._xdata, ydata)
                legline.update_from(handle)
                self._set_artist_props(legline) # after update
                legline.set_clip_box(None)
                legline.set_markersize(self.markerscale*legline.get_markersize())

                ret.append(legline)
            elif isinstance(handle, Patch):

                p = Rectangle(xy=(min(self._xdata), y-3/4*HEIGHT),
                              width = self.handlelen, height=HEIGHT/2,
                              )
                p.update_from(handle)
                self._set_artist_props(p)
                p.set_clip_box(None)
                ret.append(p)
            elif isinstance(handle, LineCollection):
                ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float)
                legline = Line2D(self._xdata, ydata)
                self._set_artist_props(legline)
                legline.set_clip_box(None)
                lw = handle.get_linewidth()[0]
                dashes = handle.get_dashes()
                color = handle.get_colors()[0]
                legline.set_color(color)
                legline.set_linewidth(lw)
                legline.set_dashes(dashes)
                ret.append(legline)

            elif isinstance(handle, RegularPolyCollection):

                p = Rectangle(xy=(min(self._xdata), y-3/4*HEIGHT),
                              width = self.handlelen, height=HEIGHT/2,
                              )
                p.set_facecolor(handle._facecolors[0])
                if handle._edgecolors != 'None':
                    p.set_edgecolor(handle._edgecolors[0])
                self._set_artist_props(p)
                p.set_clip_box(None)
                ret.append(p)

	    else:
		ret.append(None)

        return ret
예제 #9
0
파일: lines.py 프로젝트: jtomase/matplotlib
    def _draw_steps(self, renderer, gc, xt, yt):
        siz=len(xt)
        if siz<2: return
        xt2=ones((2*siz,), typecode(xt))
        xt2[0:-1:2], xt2[1:-1:2], xt2[-1]=xt, xt[1:], xt[-1]
        yt2=ones((2*siz,), typecode(yt))
        yt2[0:-1:2], yt2[1::2]=yt, yt
        gc.set_linestyle('solid')

        if self._newstyle:
            renderer.draw_lines(gc, xt2, yt2, self._transform)
        else:
            renderer.draw_lines(gc, xt2, yt2)
예제 #10
0
    def _get_numeric_clipped_data_in_range(self):
        # if the x or y clip is set, only plot the points in the
        # clipping region.  If log scale is set, only pos data will be
        # returned

        try:
            self._xc, self._yc
        except AttributeError:
            x, y = self._x, self._y
        else:
            x, y = self._xc, self._yc

        try:
            logx = self._transform.get_funcx().get_type() == LOG10
        except RuntimeError:
            logx = False  # non-separable

        try:
            logy = self._transform.get_funcy().get_type() == LOG10
        except RuntimeError:
            logy = False  # non-separable

        if not logx and not logy:
            return x, y

        if self._logcache is not None:
            waslogx, waslogy, xcache, ycache = self._logcache
            if logx == waslogx and waslogy == logy:
                return xcache, ycache

        Nx = len(x)
        Ny = len(y)

        if logx:
            indx = greater(x, 0)
        else:
            indx = ones(len(x))

        if logy:
            indy = greater(y, 0)
        else:
            indy = ones(len(y))

        ind = nonzero(logical_and(indx, indy))
        x = take(x, ind)
        y = take(y, ind)

        self._logcache = logx, logy, x, y
        return x, y
예제 #11
0
파일: lines.py 프로젝트: jtomase/matplotlib
    def set_data(self, *args):
        """
        Set the x and y data

        ACCEPTS: (array xdata, array ydata)
        """

        if len(args)==1:
            x, y = args[0]
        else:
            x, y = args

        self._x_orig = x
        self._y_orig = y

        if (self._xunits and hasattr(x, 'convert_to')):
            x = x.convert_to(self._xunits).get_value()
        if (hasattr(x, 'get_value')):
            x = x.get_value()
        if (self._yunits and hasattr(y, 'convert_to')):
            y = y.convert_to(self._yunits).get_value()
        if (hasattr(y, 'get_value')):
            y = y.get_value()

        x = ma.ravel(x)
        y = ma.ravel(y)
        if len(x)==1 and len(y)>1:
            x = x * ones(y.shape, Float)
        if len(y)==1 and len(x)>1:
            y = y * ones(x.shape, Float)

        if len(x) != len(y):
            raise RuntimeError('xdata and ydata must be the same length')

        mx = ma.getmask(x)
        my = ma.getmask(y)
        mask = ma.mask_or(mx, my)
        if mask is not ma.nomask:
            x = ma.masked_array(x, mask=mask).compressed()
            y = ma.masked_array(y, mask=mask).compressed()
            self._segments = unmasked_index_ranges(mask)
        else:
            self._segments = None

        self._x = asarray(x, Float)
        self._y = asarray(y, Float)

        self._logcache = None
예제 #12
0
파일: mlab.py 프로젝트: jtomase/matplotlib
def psd(x, NFFT=256, Fs=2, detrend=detrend_none,
        window=window_hanning, noverlap=0):
    """
    The power spectral density by Welches average periodogram method.
    The vector x is divided into NFFT length segments.  Each segment
    is detrended by function detrend and windowed by function window.
    noperlap gives the length of the overlap between segments.  The
    absolute(fft(segment))**2 of each segment are averaged to compute Pxx,
    with a scaling to correct for power loss due to windowing.  Fs is
    the sampling frequency.

    -- NFFT must be a power of 2
    -- detrend and window are functions, unlike in matlab where they are
       vectors.
    -- if length x < NFFT, it will be zero padded to NFFT
    

    Returns the tuple Pxx, freqs

    Refs:
      Bendat & Piersol -- Random Data: Analysis and Measurement
        Procedures, John Wiley & Sons (1986)

    """

    if NFFT % 2:
        raise ValueError, 'NFFT must be a power of 2'

    # zero pad x up to NFFT if it is shorter than NFFT
    if len(x)<NFFT:
        n = len(x)
        x = resize(x, (NFFT,))
        x[n:] = 0
    

    # for real x, ignore the negative frequencies
    if x.typecode()==Complex: numFreqs = NFFT
    else: numFreqs = NFFT//2+1
        
    windowVals = window(ones((NFFT,),x.typecode()))
    step = NFFT-noverlap
    ind = range(0,len(x)-NFFT+1,step)
    n = len(ind)
    Pxx = zeros((numFreqs,n), Float)
    # do the ffts of the slices
    for i in range(n):
        thisX = x[ind[i]:ind[i]+NFFT]
        thisX = windowVals*detrend(thisX)
        fx = absolute(fft(thisX))**2
        Pxx[:,i] = divide(fx[:numFreqs], norm(windowVals)**2)

    # Scale the spectrum by the norm of the window to compensate for
    # windowing loss; see Bendat & Piersol Sec 11.5.2
    if n>1:
       Pxx = mean(Pxx,1)

    freqs = Fs/NFFT*arange(numFreqs)
    Pxx.shape = len(freqs),

    return Pxx, freqs
예제 #13
0
    def _update_positions(self, renderer):
        # called from renderer to allow more precise estimates of
        # widths and heights with get_window_extent

        def get_tbounds(text):  #get text bounds in axes coords
            bbox = text.get_window_extent(renderer)
            bboxa = inverse_transform_bbox(self._transform, bbox)
            return bboxa.get_bounds()
            
        hpos = []
        for t, tabove in zip(self.texts[1:], self.texts[:-1]):
            x,y = t.get_position()
            l,b,w,h = get_tbounds(tabove)
            hpos.append( (b,h) )
            t.set_position( (x, b-0.1*h) )

        # now do the same for last line
        l,b,w,h = get_tbounds(self.texts[-1])
        hpos.append( (b,h) )
        
        for handle, tup in zip(self.handles, hpos):
            y,h = tup
            if isinstance(handle, Line2D):
                ydata = y*ones(self._xdata.shape, Float)            
                handle.set_ydata(ydata+h/2)
            elif isinstance(handle, Rectangle):
                handle.set_y(y+1/4*h)
                handle.set_height(h/2)

        # Set the data for the legend patch
        bbox = self._get_handle_text_bbox(renderer).deepcopy()
        bbox.scale(1 + self.pad, 1 + self.pad)
        l,b,w,h = bbox.get_bounds()
        self.legendPatch.set_bounds(l,b,w,h)

        BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = range(11)
        ox, oy = 0, 0                           # center


        if iterable(self._loc) and len(self._loc)==2:
            xo = self.legendPatch.get_x()
            yo = self.legendPatch.get_y()
            x, y = self._loc
            ox = x-xo
            oy = y-yo
            self._offset(ox, oy)
        else:
            if self._loc in (UL, LL, CL):           # left
                ox = self.axespad - l
            if self._loc in (BEST, UR, LR, R, CR):  # right
                ox = 1 - (l + w + self.axespad)
            if self._loc in (BEST, UR, UL, UC):     # upper
                oy = 1 - (b + h + self.axespad)
            if self._loc in (LL, LR, LC):           # lower
                oy = self.axespad - b
            if self._loc in (LC, UC, C):            # center x
                ox = (0.5-w/2)-l
            if self._loc in (CL, CR, C):            # center y
                oy = (0.5-h/2)-b
            self._offset(ox, oy)
예제 #14
0
 def _init(self):
     self._lut = ones((self.N + 3, 4), Float)
     self._lut[:-3, 0] = makeMappingArray(self.N, self._segmentdata['red'])
     self._lut[:-3, 1] = makeMappingArray(self.N, self._segmentdata['green'])
     self._lut[:-3, 2] = makeMappingArray(self.N, self._segmentdata['blue'])
     self._isinit = True
     self._set_extremes()
예제 #15
0
    def _get_handles(self, handles, texts):
        HEIGHT = self._approx_text_height()

        ret = []  # the returned legend lines
        for handle, label in zip(handles, texts):
            x, y = label.get_position()
            x -= self.HANDLELEN + self.HANDLETEXTSEP
            if isinstance(handle, Line2D):
                ydata = (y - HEIGHT / 2) * ones(self._xdata.shape, Float)
                legline = Line2D(self._xdata, ydata)
                self._set_artist_props(legline)
                legline.copy_properties(handle)
                legline.set_markersize(0.6 * legline.get_markersize())
                legline.set_data_clipping(False)
                ret.append(legline)
            elif isinstance(handle, Patch):

                p = Rectangle(
                    xy=(min(self._xdata), y - 3 / 4 * HEIGHT),
                    width=self.HANDLELEN,
                    height=HEIGHT / 2,
                )
                self._set_artist_props(p)
                p.copy_properties(handle)
                ret.append(p)
            else:
                ret.append(None)

        return ret
예제 #16
0
    def set_data(self, *args):
        """
Set the x and y data

ACCEPTS: (array xdata, array ydata)
"""

        if len(args)==1:
            x, y = args[0]
        else:
            x, y = args


        try: del self._xc, self._yc
        except AttributeError: pass

        self._x = asarray(x, Float)
        self._y = asarray(y, Float)

        if len(self._x.shape)>1: self._x = ravel(self._x)
        if len(self._y.shape)>1: self._y = ravel(self._y)


        if len(self._y)==1 and len(self._x)>1:
            self._y = self._y*ones(self._x.shape, Float)

        if len(self._x) != len(self._y):
            raise RuntimeError('xdata and ydata must be the same length')

        if self._useDataClipping: self._xsorted = self._is_sorted(self._x)

        self._logcache = None
예제 #17
0
def psd(x, NFFT=256, Fs=2, detrend=detrend_none,
        window=window_hanning, noverlap=0):
    """
    The power spectral density by Welches average periodogram method.
    The vector x is divided into NFFT length segments.  Each segment
    is detrended by function detrend and windowed by function window.
    noperlap gives the length of the overlap between segments.  The
    absolute(fft(segment))**2 of each segment are averaged to compute Pxx,
    with a scaling to correct for power loss due to windowing.  Fs is
    the sampling frequency.

    -- NFFT must be a power of 2
    -- detrend and window are functions, unlike in matlab where they are
       vectors.
    -- if length x < NFFT, it will be zero padded to NFFT
    

    Returns the tuple Pxx, freqs

    Refs:
      Bendat & Piersol -- Random Data: Analysis and Measurement
        Procedures, John Wiley & Sons (1986)

    """

    if NFFT % 2:
        raise ValueError, 'NFFT must be a power of 2'

    # zero pad x up to NFFT if it is shorter than NFFT
    if len(x)<NFFT:
        n = len(x)
        x = resize(x, (NFFT,))
        x[n:] = 0
    

    # for real x, ignore the negative frequencies
    if x.typecode()==Complex: numFreqs = NFFT
    else: numFreqs = NFFT//2+1
        
    windowVals = window(ones((NFFT,),x.typecode()))
    step = NFFT-noverlap
    ind = range(0,len(x)-NFFT+1,step)
    n = len(ind)
    Pxx = zeros((numFreqs,n), Float)
    # do the ffts of the slices
    for i in range(n):
        thisX = x[ind[i]:ind[i]+NFFT]
        thisX = windowVals*detrend(thisX)
        fx = absolute(fft(thisX))**2
        Pxx[:,i] = divide(fx[:numFreqs], norm(windowVals)**2)

    # Scale the spectrum by the norm of the window to compensate for
    # windowing loss; see Bendat & Piersol Sec 11.5.2
    if n>1:
       Pxx = mean(Pxx,1)

    freqs = Fs/NFFT*arange(numFreqs)
    Pxx.shape = len(freqs),

    return Pxx, freqs
예제 #18
0
    def _get_handles(self, handles, texts):
        HEIGHT = self._approx_text_height()

        ret = []  # the returned legend lines
        for handle, label in zip(handles, texts):
            x, y = label.get_position()
            x -= self.HANDLELEN + self.HANDLETEXTSEP
            if isinstance(handle, Line2D):
                ydata = (y - HEIGHT / 2) * ones(self._xdata.shape, Float)
                legline = Line2D(self._xdata, ydata)
                self._set_artist_props(legline)
                legline.copy_properties(handle)
                legline.set_markersize(0.6 * legline.get_markersize())
                legline.set_data_clipping(False)
                ret.append(legline)
            elif isinstance(handle, Patch):

                p = Rectangle(xy=(min(self._xdata), y - 3 / 4 * HEIGHT), width=self.HANDLELEN, height=HEIGHT / 2)
                self._set_artist_props(p)
                p.copy_properties(handle)
                ret.append(p)
            else:
                ret.append(None)

        return ret
예제 #19
0
    def set_data(self, *args):
        """
Set the x and y data

ACCEPTS: (array xdata, array ydata)
"""

        if len(args) == 1:
            x, y = args[0]
        else:
            x, y = args

        try:
            del self._xc, self._yc
        except AttributeError:
            pass

        self._x = asarray(x, Float)
        self._y = asarray(y, Float)

        if len(self._x.shape) > 1:
            self._x = ravel(self._x)
        if len(self._y.shape) > 1:
            self._y = ravel(self._y)

        if len(self._y) == 1 and len(self._x) > 1:
            self._y = self._y * ones(self._x.shape, Float)

        if len(self._x) != len(self._y):
            raise RuntimeError('xdata and ydata must be the same length')

        if self._useDataClipping: self._xsorted = self._is_sorted(self._x)

        self._logcache = None
예제 #20
0
    def set_data(self, *args):
        """
        Set the x and y data

        ACCEPTS: (array xdata, array ydata)
        """

        if len(args) == 1:
            x, y = args[0]
        else:
            x, y = args

        try:
            del self._xc, self._yc
        except AttributeError:
            pass

        self._x_orig = x
        self._y_orig = y

        x = ma.ravel(x)
        y = ma.ravel(y)
        if len(x) == 1 and len(y) > 1:
            x = x * ones(y.shape, Float)
        if len(y) == 1 and len(x) > 1:
            y = y * ones(x.shape, Float)

        if len(x) != len(y):
            raise RuntimeError("xdata and ydata must be the same length")

        mx = ma.getmask(x)
        my = ma.getmask(y)
        mask = ma.mask_or(mx, my)
        if mask is not None:
            x = ma.masked_array(x, mask=mask).compressed()
            y = ma.masked_array(y, mask=mask).compressed()
            self._segments = unmasked_index_ranges(mask)
        else:
            self._segments = None

        self._x = asarray(x, Float)
        self._y = asarray(y, Float)

        if self._useDataClipping:
            self._xsorted = self._is_sorted(self._x)

        self._logcache = None
예제 #21
0
    def set_data(self, *args):
        """
        Set the x and y data

        ACCEPTS: (array xdata, array ydata)
        """

        if len(args) == 1:
            x, y = args[0]
        else:
            x, y = args

        try:
            del self._xc, self._yc
        except AttributeError:
            pass

        self._x_orig = x
        self._y_orig = y

        x = ma.ravel(x)
        y = ma.ravel(y)
        if len(x) == 1 and len(y) > 1:
            x = x * ones(y.shape, Float)
        if len(y) == 1 and len(x) > 1:
            y = y * ones(x.shape, Float)

        if len(x) != len(y):
            raise RuntimeError('xdata and ydata must be the same length')

        mx = ma.getmask(x)
        my = ma.getmask(y)
        mask = ma.mask_or(mx, my)
        if mask is not None:
            x = ma.masked_array(x, mask=mask).compressed()
            y = ma.masked_array(y, mask=mask).compressed()
            self._segments = unmasked_index_ranges(mask)
        else:
            self._segments = None

        self._x = asarray(x, Float)
        self._y = asarray(y, Float)

        if self._useDataClipping: self._xsorted = self._is_sorted(self._x)

        self._logcache = None
예제 #22
0
 def _init(self):
     self._lut = ones((self.N + 3, 4), Float)
     self._lut[:-3, 0] = makeMappingArray(self.N, self._segmentdata['red'])
     self._lut[:-3, 1] = makeMappingArray(self.N,
                                          self._segmentdata['green'])
     self._lut[:-3, 2] = makeMappingArray(self.N, self._segmentdata['blue'])
     self._isinit = True
     self._set_extremes()
예제 #23
0
    def _get_numeric_clipped_data_in_range(self):
        # if the x or y clip is set, only plot the points in the
        # clipping region.  If log scale is set, only pos data will be
        # returned

        try:
            self._xc, self._yc
        except AttributeError:
            x, y = self._x, self._y
        else:
            x, y = self._xc, self._yc

        try:
            logx = self._transform.get_funcx().get_type() == LOG10
        except RuntimeError:
            logx = False  # non-separable

        try:
            logy = self._transform.get_funcy().get_type() == LOG10
        except RuntimeError:
            logy = False  # non-separable

        if not logx and not logy:
            return x, y

        if self._logcache is not None:
            waslogx, waslogy, xcache, ycache = self._logcache
            if logx == waslogx and waslogy == logy:
                return xcache, ycache

        Nx = len(x)
        Ny = len(y)

        if logx: indx = greater(x, 0)
        else: indx = ones(len(x))

        if logy: indy = greater(y, 0)
        else: indy = ones(len(y))

        ind = nonzero(logical_and(indx, indy))
        x = take(x, ind)
        y = take(y, ind)

        self._logcache = logx, logy, x, y
        return x, y
예제 #24
0
    def set_data(self, *args):
        """
        Set the x and y data

        ACCEPTS: (array xdata, array ydata)
        """

        if len(args) == 1:
            x, y = args[0]
        else:
            x, y = args

        try:
            del self._xc, self._yc
        except AttributeError:
            pass

        self._masked_x = None
        self._masked_y = None
        mx = ma.getmask(x)
        my = ma.getmask(y)
        if mx is not None:
            mx = ravel(mx)
            self._masked_x = x
        if my is not None:
            my = ravel(my)
            self._masked_y = y
        mask = ma.mask_or(mx, my)
        if mask is not None:
            x = ma.masked_array(ma.ravel(x), mask=mask).compressed()
            y = ma.masked_array(ma.ravel(y), mask=mask).compressed()
            self._segments = unmasked_index_ranges(mask)
        else:
            self._segments = None

        self._x = asarray(x, Float)
        self._y = asarray(y, Float)

        if len(self._x.shape) > 1:
            self._x = ravel(self._x)
        if len(self._y.shape) > 1:
            self._y = ravel(self._y)

        # What is the rationale for the following two lines?
        # And why is there not a similar pair with _x and _y reversed?
        if len(self._y) == 1 and len(self._x) > 1:
            self._y = self._y * ones(self._x.shape, Float)

        if len(self._x) != len(self._y):
            raise RuntimeError("xdata and ydata must be the same length")

        if self._useDataClipping:
            self._xsorted = self._is_sorted(self._x)

        self._logcache = None
예제 #25
0
파일: lines.py 프로젝트: jtomase/matplotlib
    def set_data(self, *args):
        """
        Set the x and y data

        ACCEPTS: (array xdata, array ydata)
        """

        if len(args) == 1:
            x, y = args[0]
        else:
            x, y = args

        try:
            del self._xc, self._yc
        except AttributeError:
            pass

        self._masked_x = None
        self._masked_y = None
        mx = ma.getmask(x)
        my = ma.getmask(y)
        if mx is not None:
            mx = ravel(mx)
            self._masked_x = x
        if my is not None:
            my = ravel(my)
            self._masked_y = y
        mask = ma.mask_or(mx, my)
        if mask is not None:
            x = ma.masked_array(ma.ravel(x), mask=mask).compressed()
            y = ma.masked_array(ma.ravel(y), mask=mask).compressed()
            self._segments = unmasked_index_ranges(mask)
        else:
            self._segments = None

        self._x = asarray(x, Float)
        self._y = asarray(y, Float)

        if len(self._x.shape) > 1:
            self._x = ravel(self._x)
        if len(self._y.shape) > 1:
            self._y = ravel(self._y)

        # What is the rationale for the following two lines?
        # And why is there not a similar pair with _x and _y reversed?
        if len(self._y) == 1 and len(self._x) > 1:
            self._y = self._y * ones(self._x.shape, Float)

        if len(self._x) != len(self._y):
            raise RuntimeError('xdata and ydata must be the same length')

        if self._useDataClipping: self._xsorted = self._is_sorted(self._x)

        self._logcache = None
예제 #26
0
    def _get_handles(self, handles, texts):
        HEIGHT = self._approx_text_height()

        ret = []  # the returned legend lines

        for handle, label in zip(handles, texts):
            x, y = label.get_position()
            x -= self.handlelen + self.handletextsep
            if isinstance(handle, Line2D):
                ydata = (y - HEIGHT / 2) * ones(self._xdata.shape, Float)
                legline = Line2D(self._xdata, ydata)
                self._set_artist_props(legline)
                legline.copy_properties(handle)
                legline.set_markersize(0.6 * legline.get_markersize())
                legline.set_data_clipping(False)
                ret.append(legline)
            elif isinstance(handle, Patch):

                p = Rectangle(
                    xy=(min(self._xdata), y - 3 / 4 * HEIGHT),
                    width=self.handlelen,
                    height=HEIGHT / 2,
                )
                p.copy_properties(handle)
                self._set_artist_props(p)
                ret.append(p)
            elif isinstance(handle, LineCollection):
                ydata = (y - HEIGHT / 2) * ones(self._xdata.shape, Float)
                legline = Line2D(self._xdata, ydata)
                self._set_artist_props(legline)
                lw = handle.get_linewidths()[0]
                color = handle.get_colors()[0]
                legline.set_color(color)
                legline.set_linewidth(lw)
                ret.append(legline)

            else:
                ret.append(None)

        return ret
예제 #27
0
    def _get_handles(self, handles, texts):
        HEIGHT = self._approx_text_height()

        ret = []   # the returned legend lines

        for handle, label in zip(handles, texts):
            x, y = label.get_position()
            x -= self.handlelen + self.handletextsep
            if isinstance(handle, Line2D):
                ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float)
                legline = Line2D(self._xdata, ydata)
                self._set_artist_props(legline)
                legline.copy_properties(handle)
                legline.set_markersize(self.markerscale*legline.get_markersize())
                legline.set_data_clipping(False)
                ret.append(legline)
            elif isinstance(handle, Patch):

                p = Rectangle(xy=(min(self._xdata), y-3/4*HEIGHT),
                              width = self.handlelen, height=HEIGHT/2,
                              )
                p.copy_properties(handle)
                self._set_artist_props(p)
                ret.append(p)
            elif isinstance(handle, LineCollection):
                ydata = (y-HEIGHT/2)*ones(self._xdata.shape, Float)
                legline = Line2D(self._xdata, ydata)
                self._set_artist_props(legline)
                lw = handle.get_linewidths()[0]
                color = handle.get_colors()[0]                
                legline.set_color(color)
                legline.set_linewidth(lw)
                ret.append(legline)
                
	    else:
		ret.append(None)
                                               
        return ret
예제 #28
0
def vander(x, N=None):
    """
    X = vander(x,N=None)

    The Vandermonde matrix of vector x.  The i-th column of X is the
    the i-th power of x.  N is the maximum power to compute; if N is
    None it defaults to len(x).

    """
    if N is None: N = len(x)
    X = ones((len(x), N), typecode(x))
    for i in range(N - 1):
        X[:, i] = x**(N - i - 1)
    return X
예제 #29
0
def vander(x,N=None):
    """
    X = vander(x,N=None)

    The Vandermonde matrix of vector x.  The i-th column of X is the
    the i-th power of x.  N is the maximum power to compute; if N is
    None it defaults to len(x).

    """
    if N is None: N=len(x)
    X = ones( (len(x),N), x.typecode())
    for i in range(N-1):
        X[:,i] = x**(N-i-1)
    return X
예제 #30
0
def specgram(x,
             NFFT=256,
             Fs=2,
             detrend=detrend_none,
             window=window_hanning,
             noverlap=128):
    """
    Compute a spectrogram of data in x.  Data are split into NFFT
    length segements and the PSD of each section is computed.  The
    windowing function window is applied to each segment, and the
    amount of overlap of each segment is specified with noverlap

    See pdf for more info.

    The returned times are the midpoints of the intervals over which
    the ffts are calculated
    """
    x = asarray(x)
    assert (NFFT > noverlap)
    if log(NFFT) / log(2) != int(log(NFFT) / log(2)):
        raise ValueError, 'NFFT must be a power of 2'

    # zero pad x up to NFFT if it is shorter than NFFT
    if len(x) < NFFT:
        n = len(x)
        x = resize(x, (NFFT, ))
        x[n:] = 0

    # for real x, ignore the negative frequencies
    if typecode(x) == Complex: numFreqs = NFFT
    else: numFreqs = NFFT // 2 + 1

    windowVals = window(ones((NFFT, ), typecode(x)))
    step = NFFT - noverlap
    ind = arange(0, len(x) - NFFT + 1, step)
    n = len(ind)
    Pxx = zeros((numFreqs, n), Float)
    # do the ffts of the slices

    for i in range(n):
        thisX = x[ind[i]:ind[i] + NFFT]
        thisX = windowVals * detrend(thisX)
        fx = absolute(fft(thisX))**2
        # Scale the spectrum by the norm of the window to compensate for
        # windowing loss; see Bendat & Piersol Sec 11.5.2
        Pxx[:, i] = divide(fx[:numFreqs], norm(windowVals)**2)
    t = 1 / Fs * (ind + NFFT / 2)
    freqs = Fs / NFFT * arange(numFreqs)

    return Pxx, freqs, t
예제 #31
0
 def get_vector(self):
     """optimise points for projection"""
     si = 0
     ei = 0
     segis = []
     points = []
     for p in self._verts:
         points.extend(p)
         ei = si + len(p)
         segis.append((si, ei))
         si = ei
     xs, ys, zs = zip(*points)
     ones = nx.ones(len(xs))
     self.vec = nx.array([xs, ys, zs, ones])
     self.segis = segis
예제 #32
0
 def get_vector(self):
     """optimise points for projection"""
     si = 0
     ei = 0
     segis = []
     points = []
     for p in self._verts:
         points.extend(p)
         ei = si+len(p)
         segis.append((si,ei))
         si = ei
     xs,ys,zs = zip(*points)
     ones = nx.ones(len(xs))
     self.vec = nx.array([xs,ys,zs,ones])
     self.segis = segis
예제 #33
0
def specgram(x, NFFT=256, Fs=2, detrend=detrend_none,
             window=window_hanning, noverlap=128):
    """
    Compute a spectrogram of data in x.  Data are split into NFFT
    length segements and the PSD of each section is computed.  The
    windowing function window is applied to each segment, and the
    amount of overlap of each segment is specified with noverlap

    See pdf for more info.

    The returned times are the midpoints of the intervals over which
    the ffts are calculated
    """

    assert(NFFT>noverlap)
    if log(NFFT)/log(2) != int(log(NFFT)/log(2)):
       raise ValueError, 'NFFT must be a power of 2'

    # zero pad x up to NFFT if it is shorter than NFFT
    if len(x)<NFFT:
        n = len(x)
        x = resize(x, (NFFT,))
        x[n:] = 0
    

    # for real x, ignore the negative frequencies
    if x.typecode()==Complex: numFreqs = NFFT
    else: numFreqs = NFFT//2+1
        
    windowVals = window(ones((NFFT,),x.typecode()))
    step = NFFT-noverlap
    ind = arange(0,len(x)-NFFT+1,step)
    n = len(ind)
    Pxx = zeros((numFreqs,n), Float)
    # do the ffts of the slices

    for i in range(n):
        thisX = x[ind[i]:ind[i]+NFFT]
        thisX = windowVals*detrend(thisX)
        fx = absolute(fft(thisX))**2
        # Scale the spectrum by the norm of the window to compensate for
        # windowing loss; see Bendat & Piersol Sec 11.5.2
        Pxx[:,i] = divide(fx[:numFreqs], norm(windowVals)**2)
    t = 1/Fs*(ind+NFFT/2)
    freqs = Fs/NFFT*arange(numFreqs)

    return Pxx, freqs, t
예제 #34
0
def styles_example(epsoutfile):
    mystyles = ['.', '-', '-"', '_ ', '6_1 ', '- . ']
    count = len(mystyles)
    x1 = 0.8*arange(2)

    g = pyxgraph(xlimits=(-0.1, 1.1), xticks=(0, 1, 1),
                 ylimits=(-1, count), yticks=(0, count-1, 1),
                 ylabel='linestyles', key=None, width=8)

    for i in xrange(count):
        y = ones(2)+i-1 
        g.pyxplot((x1, y), style="l", lw=1, color=0, lt=mystyles[i])
        g.pyxlabel((0.85, i),
                   '\\tt{'+repr(mystyles[i]).replace('_','\\_')+'}',
                   style=[pyx.text.halign.left], graphcoords=True)
        
    g.pyxsave(epsoutfile)
예제 #35
0
def styles_example(epsoutfile):
    x1 = 0.25*arange(2)
    x2 = x1+0.5-0.125
    x3 = x1+1.0-0.25
    
    g = pyxgraph(xlimits=(-0.1, 1.1), xticks=(0, 1, 1),
                 ylimits=(-1, 12), yticks=(0, 11, 1),
                 ylabel='linestyles', key=None, width=8)
    for i in xrange(12):
        y = ones(2)+i-1 
        g.pyxplot((x1, y), style="l", lw=1, color=0, lt=i)
        g.pyxplot((x2, y), style="l", lw=3, color=0, lt=i)
        g.pyxplot((x3, y), style="l", lw=1, color=0, lt=i, dl=4)
    g.pyxlabel( (0.125,1.05), "lw=1", [pyx.text.halign.center])
    g.pyxlabel( (0.5,1.05), "lw=3", [pyx.text.halign.center])
    g.pyxlabel( (0.875,1.05), "lw=1, dl=4", [pyx.text.halign.center])

    g.pyxsave(epsoutfile)
예제 #36
0
    def set_data(self, x, y):
        try: del self._xc, self._yc
        except AttributeError: pass

        self._x = asarray(x, Float)
        self._y = asarray(y, Float)

        if len(self._x.shape)>1: self._x = ravel(self._x)
        if len(self._y.shape)>1: self._y = ravel(self._y)


        if len(self._y)==1 and len(self._x)>1:
            self._y = self._y*ones(self._x.shape, Float)

        if len(self._x) != len(self._y):
            raise RuntimeError('xdata and ydata must be the same length')

        if self._useDataClipping: self._xsorted = self._is_sorted(self._x)
예제 #37
0
파일: lines.py 프로젝트: jtomase/matplotlib
    def set_data(self, x, y):
        try:
            del self._xc, self._yc
        except AttributeError:
            pass

        self._x = asarray(x, Float)
        self._y = asarray(y, Float)

        if len(self._x.shape) > 1: self._x = ravel(self._x)
        if len(self._y.shape) > 1: self._y = ravel(self._y)

        if len(self._y) == 1 and len(self._x) > 1:
            self._y = self._y * ones(self._x.shape, Float)

        if len(self._x) != len(self._y):
            raise RuntimeError('xdata and ydata must be the same length')

        if self._useDataClipping: self._xsorted = self._is_sorted(self._x)
예제 #38
0
    def _initialize_reg_tri(self, z, badmask):
        '''
        Initialize two arrays used by the low-level contour
        algorithm.  This is temporary code; most of the reg
        initialization should be done in c.

        For each masked point, we need to mark as missing
        the four regions with that point as a corner.
        '''
        imax, jmax = shape(z)
        nreg = jmax * (imax + 1) + 1
        reg = ones((1, nreg), typecode='i')
        reg[0, :jmax + 1] = 0
        reg[0, -jmax:] = 0
        for j in range(0, nreg, jmax):
            reg[0, j] = 0
        if badmask is not None:
            for i in range(imax):
                for j in range(jmax):
                    if badmask[i, j]:
                        ii = i * jmax + j
                        if ii < nreg:
                            reg[0, ii] = 0
                        ii += 1
                        if ii < nreg:
                            reg[0, ii] = 0
                        ii += jmax
                        if ii < nreg:
                            reg[0, ii] = 0
                        ii -= 1
                        if ii < nreg:
                            reg[0, ii] = 0

        triangle = zeros((imax, jmax), typecode='s')

        return reg, triangle
예제 #39
0
    def _initialize_reg_tri(self, z, badmask):
        '''
        Initialize two arrays used by the low-level contour
        algorithm.  This is temporary code; most of the reg
        initialization should be done in c.

        For each masked point, we need to mark as missing
        the four regions with that point as a corner.
        '''
        imax, jmax = shape(z)
        nreg = jmax*(imax+1)+1
        reg = ones((1, nreg), typecode = 'i')
        reg[0,:jmax+1]=0
        reg[0,-jmax:]=0
        for j in range(0, nreg, jmax):
            reg[0,j]=0
        if badmask is not None:
            for i in range(imax):
                for j in range(jmax):
                    if badmask[i,j]:
                        ii = i*jmax+j
                        if ii < nreg:
                            reg[0,ii] = 0
                        ii += 1
                        if ii < nreg:
                            reg[0,ii] = 0
                        ii += jmax
                        if ii < nreg:
                            reg[0,ii] = 0
                        ii -= 1
                        if ii < nreg:
                            reg[0,ii] = 0

        triangle = zeros((imax,jmax), typecode='s')

        return reg, triangle
예제 #40
0
def csd(x,
        y,
        NFFT=256,
        Fs=2,
        detrend=detrend_none,
        window=window_hanning,
        noverlap=0):
    """
    The cross spectral density Pxy by Welches average periodogram
    method.  The vectors x and y are divided into NFFT length
    segments.  Each segment is detrended by function detrend and
    windowed by function window.  noverlap gives the length of the
    overlap between segments.  The product of the direct FFTs of x and
    y are averaged over each segment to compute Pxy, with a scaling to
    correct for power loss due to windowing.  Fs is the sampling
    frequency.

    NFFT must be a power of 2

    Returns the tuple Pxy, freqs

    

    Refs:
      Bendat & Piersol -- Random Data: Analysis and Measurement
        Procedures, John Wiley & Sons (1986)

    """

    if NFFT % 2:
        raise ValueError, 'NFFT must be a power of 2'

    # zero pad x and y up to NFFT if they are shorter than NFFT
    if len(x) < NFFT:
        n = len(x)
        x = resize(x, (NFFT, ))
        x[n:] = 0
    if len(y) < NFFT:
        n = len(y)
        y = resize(y, (NFFT, ))
        y[n:] = 0

    # for real x, ignore the negative frequencies
    if typecode(x) == Complex: numFreqs = NFFT
    else: numFreqs = NFFT // 2 + 1

    windowVals = window(ones((NFFT, ), typecode(x)))
    step = NFFT - noverlap
    ind = range(0, len(x) - NFFT + 1, step)
    n = len(ind)
    Pxy = zeros((numFreqs, n), Complex)

    # do the ffts of the slices
    for i in range(n):
        thisX = x[ind[i]:ind[i] + NFFT]
        thisX = windowVals * detrend(thisX)
        thisY = y[ind[i]:ind[i] + NFFT]
        thisY = windowVals * detrend(thisY)
        fx = fft(thisX)
        fy = fft(thisY)
        Pxy[:, i] = conjugate(fx[:numFreqs]) * fy[:numFreqs]

    # Scale the spectrum by the norm of the window to compensate for
    # windowing loss; see Bendat & Piersol Sec 11.5.2
    if n > 1: Pxy = mean(Pxy, 1)
    Pxy = divide(Pxy, norm(windowVals)**2)
    freqs = Fs / NFFT * arange(numFreqs)
    Pxy.shape = len(freqs),
    return Pxy, freqs
예제 #41
0
def cohere_pairs(X,
                 ij,
                 NFFT=256,
                 Fs=2,
                 detrend=detrend_none,
                 window=window_hanning,
                 noverlap=0,
                 preferSpeedOverMemory=True,
                 progressCallback=donothing_callback,
                 returnPxx=False):
    """
    Cxy, Phase, freqs = cohere_pairs( X, ij, ...)
    
    Compute the coherence for all pairs in ij.  X is a
    numSamples,numCols Numeric array.  ij is a list of tuples (i,j).
    Each tuple is a pair of indexes into the columns of X for which
    you want to compute coherence.  For example, if X has 64 columns,
    and you want to compute all nonredundant pairs, define ij as

      ij = []
      for i in range(64):
          for j in range(i+1,64):
              ij.append( (i,j) )

    The other function arguments, except for 'preferSpeedOverMemory'
    (see below), are explained in the help string of 'psd'.

    Return value is a tuple (Cxy, Phase, freqs).

      Cxy -- a dictionary of (i,j) tuples -> coherence vector for that
        pair.  Ie, Cxy[(i,j) = cohere(X[:,i], X[:,j]).  Number of
        dictionary keys is len(ij)
      
      Phase -- a dictionary of phases of the cross spectral density at
        each frequency for each pair.  keys are (i,j).

      freqs -- a vector of frequencies, equal in length to either the
        coherence or phase vectors for any i,j key.  Eg, to make a coherence
        Bode plot:

          subplot(211)
          plot( freqs, Cxy[(12,19)])
          subplot(212)
          plot( freqs, Phase[(12,19)])
      
    For a large number of pairs, cohere_pairs can be much more
    efficient than just calling cohere for each pair, because it
    caches most of the intensive computations.  If N is the number of
    pairs, this function is O(N) for most of the heavy lifting,
    whereas calling cohere for each pair is O(N^2).  However, because
    of the caching, it is also more memory intensive, making 2
    additional complex arrays with approximately the same number of
    elements as X.

    The parameter 'preferSpeedOverMemory', if false, limits the
    caching by only making one, rather than two, complex cache arrays.
    This is useful if memory becomes critical.  Even when
    preferSpeedOverMemory is false, cohere_pairs will still give
    significant performace gains over calling cohere for each pair,
    and will use subtantially less memory than if
    preferSpeedOverMemory is true.  In my tests with a 43000,64 array
    over all nonredundant pairs, preferSpeedOverMemory=1 delivered a
    33% performace boost on a 1.7GHZ Athlon with 512MB RAM compared
    with preferSpeedOverMemory=0.  But both solutions were more than
    10x faster than naievly crunching all possible pairs through
    cohere.

    See test/cohere_pairs_test.py in the src tree for an example
    script that shows that this cohere_pairs and cohere give the same
    results for a given pair.

    """
    numRows, numCols = X.shape

    # zero pad if X is too short
    if numRows < NFFT:
        tmp = X
        X = zeros((NFFT, numCols), typecode(X))
        X[:numRows, :] = tmp
        del tmp

    numRows, numCols = X.shape
    # get all the columns of X that we are interested in by checking
    # the ij tuples
    seen = {}
    for i, j in ij:
        seen[i] = 1
        seen[j] = 1
    allColumns = seen.keys()
    Ncols = len(allColumns)
    del seen

    # for real X, ignore the negative frequencies
    if typecode(X) == Complex: numFreqs = NFFT
    else: numFreqs = NFFT // 2 + 1

    # cache the FFT of every windowed, detrended NFFT length segement
    # of every channel.  If preferSpeedOverMemory, cache the conjugate
    # as well
    windowVals = window(ones((NFFT, ), typecode(X)))
    ind = range(0, numRows - NFFT + 1, NFFT - noverlap)
    numSlices = len(ind)
    FFTSlices = {}
    FFTConjSlices = {}
    Pxx = {}
    slices = range(numSlices)
    normVal = norm(windowVals)**2
    for iCol in allColumns:
        progressCallback(i / Ncols, 'Cacheing FFTs')
        Slices = zeros((numSlices, numFreqs), Complex)
        for iSlice in slices:
            thisSlice = X[ind[iSlice]:ind[iSlice] + NFFT, iCol]
            thisSlice = windowVals * detrend(thisSlice)
            Slices[iSlice, :] = fft(thisSlice)[:numFreqs]

        FFTSlices[iCol] = Slices
        if preferSpeedOverMemory:
            FFTConjSlices[iCol] = conjugate(Slices)
        Pxx[iCol] = divide(mean(absolute(Slices)**2), normVal)
    del Slices, ind, windowVals

    # compute the coherences and phases for all pairs using the
    # cached FFTs
    Cxy = {}
    Phase = {}
    count = 0
    N = len(ij)
    for i, j in ij:
        count += 1
        if count % 10 == 0:
            progressCallback(count / N, 'Computing coherences')

        if preferSpeedOverMemory:
            Pxy = FFTSlices[i] * FFTConjSlices[j]
        else:
            Pxy = FFTSlices[i] * conjugate(FFTSlices[j])
        if numSlices > 1: Pxy = mean(Pxy)
        Pxy = divide(Pxy, normVal)
        Cxy[(i, j)] = divide(absolute(Pxy)**2, Pxx[i] * Pxx[j])
        Phase[(i, j)] = arctan2(Pxy.imag, Pxy.real)

    freqs = Fs / NFFT * arange(numFreqs)
    if returnPxx:
        return Cxy, Phase, freqs, Pxx
    else:
        return Cxy, Phase, freqs
예제 #42
0
def cohere_pairs( X, ij, NFFT=256, Fs=2, detrend=detrend_none,
                  window=window_hanning, noverlap=0,
                  preferSpeedOverMemory=True,
                  progressCallback=donothing_callback,
                  returnPxx=False):

    """
    Cxy, Phase, freqs = cohere_pairs( X, ij, ...)
    
    Compute the coherence for all pairs in ij.  X is a
    numSamples,numCols Numeric array.  ij is a list of tuples (i,j).
    Each tuple is a pair of indexes into the columns of X for which
    you want to compute coherence.  For example, if X has 64 columns,
    and you want to compute all nonredundant pairs, define ij as

      ij = []
      for i in range(64):
          for j in range(i+1,64):
              ij.append( (i,j) )

    The other function arguments, except for 'preferSpeedOverMemory'
    (see below), are explained in the help string of 'psd'.

    Return value is a tuple (Cxy, Phase, freqs).

      Cxy -- a dictionary of (i,j) tuples -> coherence vector for that
        pair.  Ie, Cxy[(i,j) = cohere(X[:,i], X[:,j]).  Number of
        dictionary keys is len(ij)
      
      Phase -- a dictionary of phases of the cross spectral density at
        each frequency for each pair.  keys are (i,j).

      freqs -- a vector of frequencies, equal in length to either the
        coherence or phase vectors for any i,j key.  Eg, to make a coherence
        Bode plot:

          subplot(211)
          plot( freqs, Cxy[(12,19)])
          subplot(212)
          plot( freqs, Phase[(12,19)])
      
    For a large number of pairs, cohere_pairs can be much more
    efficient than just calling cohere for each pair, because it
    caches most of the intensive computations.  If N is the number of
    pairs, this function is O(N) for most of the heavy lifting,
    whereas calling cohere for each pair is O(N^2).  However, because
    of the caching, it is also more memory intensive, making 2
    additional complex arrays with approximately the same number of
    elements as X.

    The parameter 'preferSpeedOverMemory', if false, limits the
    caching by only making one, rather than two, complex cache arrays.
    This is useful if memory becomes critical.  Even when
    preferSpeedOverMemory is false, cohere_pairs will still give
    significant performace gains over calling cohere for each pair,
    and will use subtantially less memory than if
    preferSpeedOverMemory is true.  In my tests with a 43000,64 array
    over all nonredundant pairs, preferSpeedOverMemory=1 delivered a
    33% performace boost on a 1.7GHZ Athlon with 512MB RAM compared
    with preferSpeedOverMemory=0.  But both solutions were more than
    10x faster than naievly crunching all possible pairs through
    cohere.

    See test/cohere_pairs_test.py in the src tree for an example
    script that shows that this cohere_pairs and cohere give the same
    results for a given pair.

    """
    numRows, numCols = X.shape

    # zero pad if X is too short
    if numRows < NFFT:
        tmp = X
        X = zeros( (NFFT, numCols), X.typecode())
        X[:numRows,:] = tmp
        del tmp

    numRows, numCols = X.shape
    # get all the columns of X that we are interested in by checking
    # the ij tuples
    seen = {}
    for i,j in ij:
        seen[i]=1; seen[j] = 1
    allColumns = seen.keys()
    Ncols = len(allColumns)
    del seen
    
    # for real X, ignore the negative frequencies
    if X.typecode()==Complex: numFreqs = NFFT
    else: numFreqs = NFFT//2+1

    # cache the FFT of every windowed, detrended NFFT length segement
    # of every channel.  If preferSpeedOverMemory, cache the conjugate
    # as well
    windowVals = window(ones((NFFT,), X.typecode()))
    ind = range(0, numRows-NFFT+1, NFFT-noverlap)
    numSlices = len(ind)
    FFTSlices = {}
    FFTConjSlices = {}
    Pxx = {}
    slices = range(numSlices)
    normVal = norm(windowVals)**2
    for iCol in allColumns:
        progressCallback(i/Ncols, 'Cacheing FFTs')
        Slices = zeros( (numSlices,numFreqs), Complex)
        for iSlice in slices:                    
            thisSlice = X[ind[iSlice]:ind[iSlice]+NFFT, iCol]
            thisSlice = windowVals*detrend(thisSlice)
            Slices[iSlice,:] = fft(thisSlice)[:numFreqs]
            
        FFTSlices[iCol] = Slices
        if preferSpeedOverMemory:
            FFTConjSlices[iCol] = conjugate(Slices)
        Pxx[iCol] = divide(mean(absolute(Slices)**2), normVal)
    del Slices, ind, windowVals    

    # compute the coherences and phases for all pairs using the
    # cached FFTs
    Cxy = {}
    Phase = {}
    count = 0
    N = len(ij)
    for i,j in ij:
        count +=1
        if count%10==0:
            progressCallback(count/N, 'Computing coherences')

        if preferSpeedOverMemory:
            Pxy = FFTSlices[i] * FFTConjSlices[j]
        else:
            Pxy = FFTSlices[i] * conjugate(FFTSlices[j])
        if numSlices>1: Pxy = mean(Pxy)
        Pxy = divide(Pxy, normVal)
        Cxy[(i,j)] = divide(absolute(Pxy)**2, Pxx[i]*Pxx[j])
        Phase[(i,j)] =  arctan2(Pxy.imag, Pxy.real)

    freqs = Fs/NFFT*arange(numFreqs)
    if returnPxx:
       return Cxy, Phase, freqs, Pxx
    else:
       return Cxy, Phase, freqs
예제 #43
0
def csd(x, y, NFFT=256, Fs=2, detrend=detrend_none,
        window=window_hanning, noverlap=0):
    """
    The cross spectral density Pxy by Welches average periodogram
    method.  The vectors x and y are divided into NFFT length
    segments.  Each segment is detrended by function detrend and
    windowed by function window.  noverlap gives the length of the
    overlap between segments.  The product of the direct FFTs of x and
    y are averaged over each segment to compute Pxy, with a scaling to
    correct for power loss due to windowing.  Fs is the sampling
    frequency.

    NFFT must be a power of 2

    Returns the tuple Pxy, freqs

    

    Refs:
      Bendat & Piersol -- Random Data: Analysis and Measurement
        Procedures, John Wiley & Sons (1986)

    """

    if NFFT % 2:
        raise ValueError, 'NFFT must be a power of 2'

    # zero pad x and y up to NFFT if they are shorter than NFFT
    if len(x)<NFFT:
        n = len(x)
        x = resize(x, (NFFT,))
        x[n:] = 0
    if len(y)<NFFT:
        n = len(y)
        y = resize(y, (NFFT,))
        y[n:] = 0

    # for real x, ignore the negative frequencies
    if x.typecode()==Complex: numFreqs = NFFT
    else: numFreqs = NFFT//2+1
        
    windowVals = window(ones((NFFT,),x.typecode()))
    step = NFFT-noverlap
    ind = range(0,len(x)-NFFT+1,step)
    n = len(ind)
    Pxy = zeros((numFreqs,n), Complex)

    # do the ffts of the slices
    for i in range(n):
        thisX = x[ind[i]:ind[i]+NFFT]
        thisX = windowVals*detrend(thisX)
        thisY = y[ind[i]:ind[i]+NFFT]
        thisY = windowVals*detrend(thisY)
        fx = fft(thisX)
        fy = fft(thisY)
        Pxy[:,i] = conjugate(fx[:numFreqs])*fy[:numFreqs]



    # Scale the spectrum by the norm of the window to compensate for
    # windowing loss; see Bendat & Piersol Sec 11.5.2
    if n>1: Pxy = mean(Pxy,1)
    Pxy = divide(Pxy, norm(windowVals)**2)
    freqs = Fs/NFFT*arange(numFreqs)
    Pxy.shape = len(freqs),
    return Pxy, freqs