Пример #1
0
def unmasked_index_ranges(mask, compressed=True):
    '''
    Calculate the good data ranges in a masked 1-D array, based on mask.

    Returns Nx2 array with each row the start and stop indices
    for slices of the compressed array corresponding to each of N
    uninterrupted runs of unmasked values.
    If optional argument compressed is False, it returns the
    start and stop indices into the original array, not the
    compressed array.
    In either case, an empty array is returned if there are no
    unmasked values.

    Example:

    y = ma.array(arange(5), mask = [0,0,1,0,0])
    #ii = unmasked_index_ranges(y.mask())
    ii = unmasked_index_ranges(ma.getmask(y))
        # returns [[0,2,] [2,4,]]

    y.compressed().filled()[ii[1,0]:ii[1,1]]
        # returns array [3,4,]
        # (The 'filled()' method converts the masked array to a numerix array.)

    #i0, i1 = unmasked_index_ranges(y.mask(), compressed=False)
    i0, i1 = unmasked_index_ranges(ma.getmask(y), compressed=False)
        # returns [[0,3,] [2,5,]]

    y.filled()[ii[1,0]:ii[1,1]]
        # returns array [3,4,]

    '''
    m = concatenate(((1, ), mask, (1, )))
    indices = arange(len(mask) + 1)
    mdif = m[1:] - m[:-1]
    i0 = compress(mdif == -1, indices)
    i1 = compress(mdif == 1, indices)
    assert len(i0) == len(i1)
    if not compressed:
        if len(i1):
            return concatenate((i0[:, ma.NewAxis], i1[:, ma.NewAxis]), axis=1)
        else:
            return zeros((0, 0), 'i')
    seglengths = i1 - i0
    breakpoints = cumsum(seglengths)
    try:
        ic0 = concatenate(((0, ), breakpoints[:-1]))
        ic1 = breakpoints
        return concatenate((ic0[:, ma.NewAxis], ic1[:, ma.NewAxis]), axis=1)
    except:
        return zeros((0, 0), 'i')
Пример #2
0
def unmasked_index_ranges(mask, compressed = True):
    '''
    Calculate the good data ranges in a masked 1-D array, based on mask.

    Returns Nx2 array with each row the start and stop indices
    for slices of the compressed array corresponding to each of N
    uninterrupted runs of unmasked values.
    If optional argument compressed is False, it returns the
    start and stop indices into the original array, not the
    compressed array.
    In either case, an empty array is returned if there are no
    unmasked values.

    Example:

    y = ma.array(arange(5), mask = [0,0,1,0,0])
    #ii = unmasked_index_ranges(y.mask())
    ii = unmasked_index_ranges(ma.getmask(y))
        # returns [[0,2,] [2,4,]]

    y.compressed().filled()[ii[1,0]:ii[1,1]]
        # returns array [3,4,]
        # (The 'filled()' method converts the masked array to a numerix array.)

    #i0, i1 = unmasked_index_ranges(y.mask(), compressed=False)
    i0, i1 = unmasked_index_ranges(ma.getmask(y), compressed=False)
        # returns [[0,3,] [2,5,]]

    y.filled()[ii[1,0]:ii[1,1]]
        # returns array [3,4,]

    '''
    m = concatenate(((1,), mask, (1,)))
    indices = arange(len(mask) + 1)
    mdif = m[1:] - m[:-1]
    i0 = compress(mdif == -1, indices)
    i1 = compress(mdif == 1, indices)
    assert len(i0) == len(i1)
    if not compressed:
        if len(i1):
            return concatenate((i0[:, ma.NewAxis], i1[:, ma.NewAxis]), axis=1)
        else:
            return zeros((0,0), 'i')
    seglengths = i1 - i0
    breakpoints = cumsum(seglengths)
    try:
        ic0 = concatenate(((0,), breakpoints[:-1]))
        ic1 = breakpoints
        return concatenate((ic0[:, ma.NewAxis], ic1[:, ma.NewAxis]), axis=1)
    except:
        return zeros((0,0), 'i')
Пример #3
0
def hist(y, bins=10, normed=0):
    """
    Return the histogram of y with bins equally sized bins.  If bins
    is an array, use the bins.  Return value is
    (n,x) where n is the count for each bin in x

    If normed is False, return the counts in the first element of the
    return tuple.  If normed is True, return the probability density
    n/(len(y)*dbin)

    If y has rank>1, it will be raveled
    Credits: the Numeric 22 documentation

    

    """
    y = asarray(y)
    if len(y.shape)>1: y = ravel(y)

    if not iterable(bins):       
        ymin, ymax = min(y), max(y)
        if ymin==ymax:
            ymin -= 0.5
            ymax += 0.5
        bins = linspace(ymin, ymax, bins)

    n = searchsorted(sort(y), bins)
    n = diff(concatenate([n, [len(y)]]))
    if normed:
       db = bins[1]-bins[0]
       return 1/(len(y)*db)*n, bins
    else:
       return n, bins
Пример #4
0
def hist(y, bins=10, normed=0):
    """
    Return the histogram of y with bins equally sized bins.  If bins
    is an array, use the bins.  Return value is
    (n,x) where n is the count for each bin in x

    If normed is False, return the counts in the first element of the
    return tuple.  If normed is True, return the probability density
    n/(len(y)*dbin)

    If y has rank>1, it will be raveled
    Credits: the Numeric 22 documentation

    

    """
    y = asarray(y)
    if len(y.shape) > 1: y = ravel(y)

    if not iterable(bins):
        ymin, ymax = min(y), max(y)
        if ymin == ymax:
            ymin -= 0.5
            ymax += 0.5
        bins = linspace(ymin, ymax, bins)

    n = searchsorted(sort(y), bins)
    n = diff(concatenate([n, [len(y)]]))
    if normed:
        db = bins[1] - bins[0]
        return 1 / (len(y) * db) * n, bins
    else:
        return n, bins
Пример #5
0
    def plot_surface(self, X, Y, Z, *args, **kwargs):
        had_data = self.has_data()

        rows, cols = Z.shape
        tX,tY,tZ = nx.transpose(X), nx.transpose(Y), nx.transpose(Z)
        rstride = cbook.popd(kwargs, 'rstride', 10)
        cstride = cbook.popd(kwargs, 'cstride', 10)
        #
        polys = []
        boxes = []
        for rs in nx.arange(0,rows,rstride):
            for cs in nx.arange(0,cols,cstride):
                ps = []
                corners = []
                for a,ta in [(X,tX),(Y,tY),(Z,tZ)]:
                    ztop = a[rs][cs:min(cols-1,cs+cstride)]
                    zleft = ta[min(cols-1,cs+cstride)][rs:min(rows,rs+rstride+1)]
                    zbase = a[min(rows-1,rs+rstride)][cs:min(cols,cs+cstride+1):]
                    zbase = zbase[::-1]
                    zright = ta[cs][rs:min(rows-1,rs+rstride):]
                    zright = zright[::-1]
                    corners.append([ztop[0],ztop[-1],zbase[0],zbase[-1]])
                    z = nx.concatenate((ztop,zleft,zbase,zright))
                    ps.append(z)
                boxes.append(map(nx.array,zip(*corners)))
                polys.append(zip(*ps))
        #
        lines = []
        shade = []
        for box in boxes:
            n = proj3d.cross(box[0]-box[1],
                         box[0]-box[2])
            n = n/proj3d.mod(n)*5
            shade.append(nx.dot(n,[-1,-1,0.5]))
            lines.append((box[0],n+box[0]))
        #
        color = nx.array([0,0,1,1])
        norm = normalize(min(shade),max(shade))
        colors = [color * (0.5+norm(v)*0.5) for v in shade]
        for c in colors: c[3] = 1
        polyc = art3d.Poly3DCollection(polys, facecolors=colors, *args, **kwargs)
        polyc._zsort = 1
        self.add_collection(polyc)
        #
        self.auto_scale_xyz(X,Y,Z, had_data)
        return polyc
Пример #6
0
def levypdf(x, gamma, alpha):
    "Returm the levy pdf evaluated at x for params gamma, alpha"

    N = len(x)

    if N % 2 != 0:
        raise ValueError, 'x must be an event length array; try\n' + \
              'x = linspace(minx, maxx, N), where N is even'

    dx = x[1] - x[0]

    f = 1 / (N * dx) * arange(-N / 2, N / 2, Float)

    ind = concatenate([arange(N / 2, N, Int), arange(N / 2, Int)])
    df = f[1] - f[0]
    cfl = exp(-gamma * absolute(2 * pi * f)**alpha)

    px = fft(take(cfl, ind) * df).astype(Float)
    return take(px, ind)
Пример #7
0
 def labels(self, inline):
     levels = self.label_levels
     fslist = self.fslist
     trans = self.ax.transData
     colors = self.label_mappable.to_rgba(self.label_cvalues)
     fmt = self.fmt
     for icon, lev, color, cvalue, fsize in zip(self.label_indices,
                                                self.label_levels, colors,
                                                self.label_cvalues, fslist):
         con = self.collections[icon]
         lw = self.get_label_width(lev, fmt, fsize)
         additions = []
         for segNum, linecontour in enumerate(con._segments):
             # for closed contours add one more point to
             # avoid division by zero
             if all(linecontour[0] == linecontour[-1]):
                 linecontour = concatenate(
                     (linecontour, linecontour[1][newaxis, :]))
                 #linecontour.append(linecontour[1])
             # transfer all data points to screen coordinates
             slc = trans.seq_xy_tups(linecontour)
             if self.print_label(slc, lw):
                 x, y, rotation, ind = self.locate_label(slc, lw)
                 # transfer the location of the label back to
                 # data coordinates
                 dx, dy = trans.inverse_xy_tup((x, y))
                 t = Text(dx,
                          dy,
                          rotation=rotation,
                          horizontalalignment='center',
                          verticalalignment='center')
                 text = self.get_text(lev, fmt)
                 self.set_label_props(t, text, color)
                 self.cl.append(t)
                 self.cl_cvalues.append(cvalue)
                 if inline:
                     new = self.break_linecontour(linecontour, rotation, lw,
                                                  ind)
                     con._segments[segNum] = new[0]
                     additions.append(new[1])
         con._segments.extend(additions)
Пример #8
0
 def labels(self, inline):
     levels = self.label_levels
     fslist = self.fslist
     trans = self.ax.transData
     colors = self.label_mappable.to_rgba(self.label_cvalues)
     fmt = self.fmt
     for icon, lev, color, cvalue, fsize in zip(self.label_indices,
                                       self.label_levels,
                                       colors,
                                       self.label_cvalues, fslist):
         con = self.collections[icon]
         lw = self.get_label_width(lev, fmt, fsize)
         additions = []
         for segNum, linecontour in enumerate(con._segments):
             # for closed contours add one more point to
             # avoid division by zero
             if all(linecontour[0] == linecontour[-1]):
                 linecontour = concatenate((linecontour,
                                            linecontour[1][newaxis,:]))
                 #linecontour.append(linecontour[1])
             # transfer all data points to screen coordinates
             slc = trans.seq_xy_tups(linecontour)
             if self.print_label(slc,lw):
                 x,y, rotation, ind  = self.locate_label(slc, lw)
                 # transfer the location of the label back to
                 # data coordinates
                 dx,dy = trans.inverse_xy_tup((x,y))
                 t = Text(dx, dy, rotation = rotation,
                          horizontalalignment='center',
                          verticalalignment='center')
                 text = self.get_text(lev,fmt)
                 self.set_label_props(t, text, color)
                 self.cl.append(t)
                 self.cl_cvalues.append(cvalue)
                 if inline:
                     new = self.break_linecontour(linecontour, rotation,
                                                    lw, ind)
                     con._segments[segNum] = new[0]
                     additions.append(new[1])
         con._segments.extend(additions)
Пример #9
0
def levypdf(x, gamma, alpha):
   "Returm the levy pdf evaluated at x for params gamma, alpha"

   N = len(x)

   if N%2 != 0:
      raise ValueError, 'x must be an event length array; try\n' + \
            'x = linspace(minx, maxx, N), where N is even'
   

   dx = x[1]-x[0]


   f = 1/(N*dx)*arange(-N/2, N/2, Float)

   ind = concatenate([arange(N/2, N, Int),
                      arange(N/2,Int)])
   df = f[1]-f[0]
   cfl = exp(-gamma*absolute(2*pi*f)**alpha)

   px = fft(take(cfl,ind)*df).astype(Float)
   return take(px, ind)
Пример #10
0
    def break_linecontour(self, linecontour, rot, labelwidth, ind):
        "break a contour in two contours at the location of the label"
        lcsize = len(linecontour)
        hlw = int(labelwidth / 2)

        #length of label in screen coords
        ylabel = abs(hlw * sin(rot * pi / 180))
        xlabel = abs(hlw * cos(rot * pi / 180))

        trans = self.ax.transData

        slc = trans.seq_xy_tups(linecontour)
        x, y = slc[ind]
        xx = asarray(slc)[:, 0].copy()
        yy = asarray(slc)[:, 1].copy()

        #indices which are under the label
        inds = nonzero(((xx < x + xlabel) & (xx > x - xlabel))
                       & ((yy < y + ylabel) & (yy > y - ylabel)))

        if len(inds) > 0:
            #if the label happens to be over the beginning of the
            #contour, the entire contour is removed, i.e.
            #indices to be removed are
            #inds= [0,1,2,3,305,306,307]
            #should rewrite this in a better way
            linds = nonzero(inds[1:] - inds[:-1] != 1)
            if inds[0] == 0 and len(linds) != 0:
                ii = inds[linds[0]]
                lc1 = linecontour[ii + 1:inds[ii + 1]]
                lc2 = []

            else:
                lc1 = linecontour[:inds[0]]
                lc2 = linecontour[inds[-1] + 1:]

        else:
            lc1 = linecontour[:ind]
            lc2 = linecontour[ind + 1:]

        if rot < 0:
            new_x1, new_y1 = x - xlabel, y + ylabel
            new_x2, new_y2 = x + xlabel, y - ylabel
        else:
            new_x1, new_y1 = x - xlabel, y - ylabel
            new_x2, new_y2 = x + xlabel, y + ylabel

        new_x1d, new_y1d = trans.inverse_xy_tup((new_x1, new_y1))
        new_x2d, new_y2d = trans.inverse_xy_tup((new_x2, new_y2))
        new_xy1 = array(((new_x1d, new_y1d), ))
        new_xy2 = array(((new_x2d, new_y2d), ))

        if rot > 0:
            if (len(lc1) > 0 and (lc1[-1][0] <= new_x1d)
                    and (lc1[-1][1] <= new_y1d)):
                lc1 = concatenate((lc1, new_xy1))
                #lc1.append((new_x1d, new_y1d))

            if (len(lc2) > 0 and (lc2[0][0] >= new_x2d)
                    and (lc2[0][1] >= new_y2d)):
                lc2 = concatenate((new_xy2, lc2))
                #lc2.insert(0, (new_x2d, new_y2d))
        else:
            if (len(lc1) > 0
                    and ((lc1[-1][0] <= new_x1d) and (lc1[-1][1] >= new_y1d))):
                lc1 = concatenate((lc1, new_xy1))
                #lc1.append((new_x1d, new_y1d))

            if (len(lc2) > 0
                    and ((lc2[0][0] >= new_x2d) and (lc2[0][1] <= new_y2d))):
                lc2 = concatenate((new_xy2, lc2))
                #lc2.insert(0, (new_x2d, new_y2d))

        return [lc1, lc2]
Пример #11
0
    def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False, \
        head_width=None, head_length=None, shape='full', overhang=0, \
        head_starts_at_zero=False,**kwargs):
        """Returns a new Arrow.

        length_includes_head: True if head is counted in calculating the length.

        shape: ['full', 'left', 'right']

        overhang: distance that the arrow is swept back (0 overhang means
        triangular shape).

        head_starts_at_zero: if True, the head starts being drawn at coordinate
        0 instead of ending at coordinate 0.
        """
        if head_width is None:
            head_width = 3 * width
        if head_length is None:
            head_length = 1.5 * head_width

        distance = sqrt(dx**2 + dy**2)
        if length_includes_head:
            length = distance
        else:
            length = distance + head_length
        if not length:
            verts = []  #display nothing if empty
        else:
            #start by drawing horizontal arrow, point at (0,0)
            hw, hl, hs, lw = head_width, head_length, overhang, width
            left_half_arrow = array([
                [0.0, 0.0],  #tip
                [-hl, -hw / 2.0],  #leftmost
                [-hl * (1 - hs), -lw / 2.0],  #meets stem
                [-length, -lw / 2.0],  #bottom left
                [-length, 0],
            ])
            #if we're not including the head, shift up by head length
            if not length_includes_head:
                left_half_arrow += [head_length, 0]
            #if the head starts at 0, shift up by another head length
            if head_starts_at_zero:
                left_half_arrow += [head_length / 2.0, 0]
            #figure out the shape, and complete accordingly
            if shape == 'left':
                coords = left_half_arrow
            else:
                right_half_arrow = left_half_arrow * [1, -1]
                if shape == 'right':
                    coords = right_half_arrow
                elif shape == 'full':
                    coords = concatenate(
                        [left_half_arrow, right_half_arrow[::-1]])
                else:
                    raise ValueError, "Got unknown shape: %s" % shape
            cx = float(dx) / distance
            sx = float(dy) / distance
            M = array([[cx, sx], [-sx, cx]])
            verts = matrixmultiply(coords, M) + (x + dx, y + dy)

        Polygon.__init__(self, map(tuple, verts), **kwargs)
Пример #12
0
    def break_linecontour(self, linecontour, rot, labelwidth, ind):
        "break a contour in two contours at the location of the label"
        lcsize = len(linecontour)
        hlw = int(labelwidth/2)

        #length of label in screen coords
        ylabel = abs(hlw * sin(rot*pi/180))
        xlabel = abs(hlw * cos(rot*pi/180))

        trans = self.ax.transData

        slc = trans.seq_xy_tups(linecontour)
        x,y = slc[ind]
        xx= asarray(slc)[:,0].copy()
        yy=asarray(slc)[:,1].copy()

        #indices which are under the label
        inds=nonzero(((xx < x+xlabel) & (xx > x-xlabel)) &
                     ((yy < y+ylabel) & (yy > y-ylabel)))

        if len(inds) >0:
            #if the label happens to be over the beginning of the
            #contour, the entire contour is removed, i.e.
            #indices to be removed are
            #inds= [0,1,2,3,305,306,307]
            #should rewrite this in a better way
            linds = nonzero(inds[1:]- inds[:-1] != 1)
            if inds[0] == 0 and len(linds) != 0:
                ii = inds[linds[0]]
                lc1 =linecontour[ii+1:inds[ii+1]]
                lc2 = []

            else:
                lc1=linecontour[:inds[0]]
                lc2= linecontour[inds[-1]+1:]

        else:
            lc1=linecontour[:ind]
            lc2 = linecontour[ind+1:]


        if rot <0:
            new_x1, new_y1 = x-xlabel, y+ylabel
            new_x2, new_y2 = x+xlabel, y-ylabel
        else:
            new_x1, new_y1 = x-xlabel, y-ylabel
            new_x2, new_y2 = x+xlabel, y+ylabel

        new_x1d, new_y1d = trans.inverse_xy_tup((new_x1, new_y1))
        new_x2d, new_y2d = trans.inverse_xy_tup((new_x2, new_y2))
        new_xy1 = array(((new_x1d, new_y1d),))
        new_xy2 = array(((new_x2d, new_y2d),))


        if rot > 0:
            if (len(lc1) > 0 and (lc1[-1][0] <= new_x1d)
                             and (lc1[-1][1] <= new_y1d)):
                lc1 = concatenate((lc1, new_xy1))
                #lc1.append((new_x1d, new_y1d))

            if (len(lc2) > 0 and (lc2[0][0] >= new_x2d)
                             and (lc2[0][1] >= new_y2d)):
                lc2 = concatenate((new_xy2, lc2))
                #lc2.insert(0, (new_x2d, new_y2d))
        else:
            if (len(lc1) > 0 and ((lc1[-1][0] <= new_x1d)
                             and (lc1[-1][1] >= new_y1d))):
                lc1 = concatenate((lc1, new_xy1))
                #lc1.append((new_x1d, new_y1d))

            if (len(lc2) > 0 and ((lc2[0][0] >= new_x2d)
                             and (lc2[0][1] <= new_y2d))):
                lc2 = concatenate((new_xy2, lc2))
                #lc2.insert(0, (new_x2d, new_y2d))

        return [lc1,lc2]
Пример #13
0
    def __init__(
        self,
        x,
        y,
        dx,
        dy,
        width=0.001,
        length_includes_head=False,
        head_width=None,
        head_length=None,
        shape="full",
        overhang=0,
        head_starts_at_zero=False,
        **kwargs
    ):
        """Returns a new Arrow.

        length_includes_head: True if head is counted in calculating the length.

        shape: ['full', 'left', 'right']

        overhang: distance that the arrow is swept back (0 overhang means
        triangular shape).

        head_starts_at_zero: if True, the head starts being drawn at coordinate
        0 instead of ending at coordinate 0.
        """
        if head_width is None:
            head_width = 3 * width
        if head_length is None:
            head_length = 1.5 * head_width

        distance = sqrt(dx ** 2 + dy ** 2)
        if length_includes_head:
            length = distance
        else:
            length = distance + head_length
        if not length:
            verts = []  # display nothing if empty
        else:
            # start by drawing horizontal arrow, point at (0,0)
            hw, hl, hs, lw = head_width, head_length, overhang, width
            left_half_arrow = array(
                [
                    [0.0, 0.0],  # tip
                    [-hl, -hw / 2.0],  # leftmost
                    [-hl * (1 - hs), -lw / 2.0],  # meets stem
                    [-length, -lw / 2.0],  # bottom left
                    [-length, 0],
                ]
            )
            # if we're not including the head, shift up by head length
            if not length_includes_head:
                left_half_arrow += [head_length, 0]
            # if the head starts at 0, shift up by another head length
            if head_starts_at_zero:
                left_half_arrow += [head_length / 2.0, 0]
            # figure out the shape, and complete accordingly
            if shape == "left":
                coords = left_half_arrow
            else:
                right_half_arrow = left_half_arrow * [1, -1]
                if shape == "right":
                    coords = right_half_arrow
                elif shape == "full":
                    coords = concatenate([left_half_arrow, right_half_arrow[::-1]])
                else:
                    raise ValueError, "Got unknown shape: %s" % shape
            cx = float(dx) / distance
            sx = float(dy) / distance
            M = array([[cx, sx], [-sx, cx]])
            verts = matrixmultiply(coords, M) + (x + dx, y + dy)

        Polygon.__init__(self, map(tuple, verts), **kwargs)