Esempio n. 1
0
def fix(x):

    """
    Rounds towards zero.
    x_rounded = fix(x) rounds the elements of x to the nearest integers
    towards zero.
    For negative numbers is equivalent to ceil and for positive to floor.
    """
    
    dim = numerix.shape(x)
    if MLab.rank(x)==2:
        y = numerix.reshape(x,(1,dim[0]*dim[1]))[0]
        y = y.tolist()
    elif MLab.rank(x)==1:
        y = x
    else:
        y = [x]
    for i in range(len(y)):
	if y[i]>0:
		y[i] = numerix.floor(y[i])
	else:
		y[i] = numerix.ceil(y[i])
    if MLab.rank(x)==2:
        x = numerix.reshape(y,dim)
    elif MLab.rank(x)==0:
        x = y[0]
    return x
Esempio n. 2
0
def fix(x):

    """
    Rounds towards zero.
    x_rounded = fix(x) rounds the elements of x to the nearest integers
    towards zero.
    For negative numbers is equivalent to ceil and for positive to floor.
    """
    
    dim = numerix.shape(x)
    if numerix.mlab.rank(x)==2:
        y = reshape(x,(1,dim[0]*dim[1]))[0]
        y = y.tolist()
    elif numerix.mlab.rank(x)==1:
        y = x
    else:
        y = [x]
    for i in range(len(y)):
	if y[i]>0:
		y[i] = floor(y[i])
	else:
		y[i] = ceil(y[i])
    if numerix.mlab.rank(x)==2:
        x = reshape(y,dim)
    elif numerix.mlab.rank(x)==0:
        x = y[0]
    return x
Esempio n. 3
0
 def _process_linewidths(self):
     linewidths = self.linewidths
     Nlev = len(self.levels)
     if linewidths is None:
         tlinewidths = [rcParams['lines.linewidth']] *Nlev
     else:
         if iterable(linewidths) and len(linewidths) < Nlev:
             linewidths = list(linewidths) * int(ceil(Nlev/len(linewidths)))
         elif not iterable(linewidths) and type(linewidths) in [int, float]:
             linewidths = [linewidths] * Nlev
         tlinewidths = [(w,) for w in linewidths]
     return tlinewidths
Esempio n. 4
0
 def _process_linewidths(self):
     linewidths = self.linewidths
     Nlev = len(self.levels)
     if linewidths is None:
         tlinewidths = [rcParams['lines.linewidth']] *Nlev
     else:
         if iterable(linewidths) and len(linewidths) < Nlev:
             linewidths = list(linewidths) * int(ceil(Nlev/len(linewidths)))
         elif not iterable(linewidths) and type(linewidths) in [int, float]:
             linewidths = [linewidths] * Nlev
         tlinewidths = [(w,) for w in linewidths]
     return tlinewidths
Esempio n. 5
0
    def locate_label(self, linecontour, labelwidth):
        """find a good place to plot a label (relatively flat
        part of the contour) and the angle of rotation for the
        text object
        """

        nsize = len(linecontour)
        if labelwidth > 1:
            xsize = int(ceil(nsize / labelwidth))
        else:
            xsize = 1
        if xsize == 1:
            ysize = nsize
        else:
            ysize = labelwidth

        XX = resize(asarray(linecontour)[:, 0], (xsize, ysize))
        YY = resize(asarray(linecontour)[:, 1], (xsize, ysize))

        yfirst = YY[:, 0]
        ylast = YY[:, -1]
        xfirst = XX[:, 0]
        xlast = XX[:, -1]
        s = ((reshape(yfirst, (xsize, 1)) - YY) *
             (reshape(xlast, (xsize, 1)) - reshape(xfirst, (xsize, 1))) -
             (reshape(xfirst, (xsize, 1)) - XX) *
             (reshape(ylast, (xsize, 1)) - reshape(yfirst, (xsize, 1))))
        L = sqrt((xlast - xfirst)**2 + (ylast - yfirst)**2)
        dist = add.reduce(([(abs(s)[i] / L[i]) for i in range(xsize)]), -1)
        x, y, ind = self.get_label_coords(dist, XX, YY, ysize, labelwidth)
        #print 'ind, x, y', ind, x, y
        angle = arctan2(ylast - yfirst, xlast - xfirst)
        rotation = angle[ind] * 180 / pi
        if rotation > 90:
            rotation = rotation - 180
        if rotation < -90:
            rotation = 180 + rotation

        # There must be a more efficient way...
        lc = [tuple(l) for l in linecontour]
        dind = lc.index((x, y))
        #print 'dind', dind
        #dind = list(linecontour).index((x,y))

        return x, y, rotation, dind
Esempio n. 6
0
    def locate_label(self, linecontour, labelwidth):
        """find a good place to plot a label (relatively flat
        part of the contour) and the angle of rotation for the
        text object
        """

        nsize= len(linecontour)
        if labelwidth > 1:
            xsize = int(ceil(nsize/labelwidth))
        else:
            xsize = 1
        if xsize == 1:
            ysize = nsize
        else:
            ysize = labelwidth

        XX = resize(asarray(linecontour)[:,0],(xsize, ysize))
        YY = resize(asarray(linecontour)[:,1],(xsize,ysize))

        yfirst = YY[:,0]
        ylast = YY[:,-1]
        xfirst = XX[:,0]
        xlast = XX[:,-1]
        s = ( (reshape(yfirst, (xsize,1))-YY) *
              (reshape(xlast,(xsize,1)) - reshape(xfirst,(xsize,1)))
              - (reshape(xfirst,(xsize,1))-XX)
              * (reshape(ylast,(xsize,1)) - reshape(yfirst,(xsize,1))) )
        L=sqrt((xlast-xfirst)**2+(ylast-yfirst)**2)
        dist = add.reduce(([(abs(s)[i]/L[i]) for i in range(xsize)]),-1)
        x,y,ind = self.get_label_coords(dist, XX, YY, ysize, labelwidth)
        #print 'ind, x, y', ind, x, y
        angle = arctan2(ylast - yfirst, xlast - xfirst)
        rotation = angle[ind]*180/pi
        if rotation > 90:
            rotation = rotation -180
        if rotation < -90:
            rotation = 180 + rotation

        # There must be a more efficient way...
        lc = [tuple(l) for l in linecontour]
        dind = lc.index((x,y))
        #print 'dind', dind
        #dind = list(linecontour).index((x,y))

        return x,y, rotation, dind
Esempio n. 7
0
    def contour(self, *args, **kwargs):
        """
        contour(self, *args, **kwargs)

        Function signatures

        contour(Z) - make a contour plot of an array Z. The level
                 values are chosen automatically.

        contour(X,Y,Z) - X,Y specify the (x,y) coordinates of the surface

        contour(Z,N) and contour(X,Y,Z,N) - draw N contour lines overriding
                         the automatic value

        contour(Z,V) and contour(X,Y,Z,V) - draw len(V) contour lines,
                       at the values specified in V (array, list, tuple)

        contour(Z, **kwargs) - Use keyword args to control colors, linewidth,
                    origin, cmap ... see below

        [L,C] = contour(...) returns a list of levels and a silent_list of LineCollections

        Optional keywork args are shown with their defaults below (you must
        use kwargs for these):

            * colors = None: one of these:
              - a tuple of matplotlib color args (string, float, rgb, etc),
              different levels will be plotted in different colors in the order
              specified

              -  one string color, e.g. colors = 'r' or colors = 'red', all levels
              will be plotted in this color

              - if colors == None, the default colormap will be used

            * alpha=1.0 : the alpha blending value

            * cmap = None: a cm Colormap instance from matplotlib.cm.

            * origin = None: 'upper'|'lower'|'image'|None.
              If 'image', the rc value for image.origin will be used.
              If None (default), the first value of Z will correspond
              to the lower left corner, location (0,0).
              This keyword is active only if contourf is called with
              one or two arguments, that is, without explicitly
              specifying X and Y.

            * extent = None: (x0,x1,y0,y1); also active only if X and Y
              are not specified.

            * badmask = None: array with dimensions of Z, and with values
              of zero at locations corresponding to valid data, and one
              at locations where the value of Z should be ignored.
              This is experimental.  It presently works for edge regions
              for line and filled contours, but for interior regions it
              works correctly only for line contours.  The badmask kwarg
              may go away in the future, to be replaced by the use of
              NaN value in Z and/or the use of a masked array in Z.

            * linewidths = None: or one of these:
              - a number - all levels will be plotted with this linewidth,
                e.g. linewidths = 0.6

              - a tuple of numbers, e.g. linewidths = (0.4, 0.8, 1.2) different
                levels will be plotted with different linewidths in the order
                specified

              - if linewidths == None, the default width in lines.linewidth in
                .matplotlibrc is used

            * fmt = '1.3f': a format string for adding a label to each collection.
              Useful for auto-legending.

        """

        alpha = kwargs.get('alpha', 1.0)
        linewidths = kwargs.get('linewidths', None)
        fmt = kwargs.get('fmt', '%1.3f')
        origin = kwargs.get('origin', None)
        extent = kwargs.get('extent', None)
        cmap = kwargs.get('cmap', None)
        colors = kwargs.get('colors', None)
        badmask = kwargs.get('badmask', None)

        if cmap is not None: assert (isinstance(cmap, Colormap))
        if origin is not None: assert (origin in ['lower', 'upper', 'image'])
        if extent is not None: assert (len(extent) == 4)
        if colors is not None and cmap is not None:
            raise RuntimeError('Either colors or cmap must be None')
        # todo: shouldn't this use the current image rather than the rc param?
        if origin == 'image': origin = rcParams['image.origin']

        x, y, z, lev = self._contour_args(False, badmask, origin, extent,
                                          *args)

        # Manipulate the plot *after* checking the input arguments.
        if not self.ax.ishold(): self.ax.cla()

        Nlev = len(lev)
        if cmap is None:
            if colors is None:
                Ncolors = Nlev
            else:
                Ncolors = len(colors)
        else:
            Ncolors = Nlev

        reg, triangle = self._initialize_reg_tri(z, badmask)

        tcolors, mappable, collections = self._process_colors(
            z, colors, alpha, lev, cmap)

        if linewidths == None:
            tlinewidths = [rcParams['lines.linewidth']] * Nlev
        else:
            if iterable(linewidths) and len(linewidths) < Nlev:
                linewidths = list(linewidths) * int(
                    ceil(Nlev / len(linewidths)))
            elif not iterable(linewidths) and type(linewidths) in [int, float]:
                linewidths = [linewidths] * Nlev
            tlinewidths = [(w, ) for w in linewidths]

        region = 0
        for level, color, width in zip(lev, tcolors, tlinewidths):
            ntotal, nparts = _contour.GcInit1(x, y, reg, triangle, region, z,
                                              level)
            np = zeros((nparts, ), typecode='l')
            xp = zeros((ntotal, ), Float64)
            yp = zeros((ntotal, ), Float64)
            nlist = _contour.GcTrace(np, xp, yp)
            col = LineCollection(nlist)
            col.set_color(color)
            col.set_linewidth(width)

            if level < 0.0 and Ncolors == 1:
                col.set_linestyle((0, (6., 6.)), )
                #print "setting dashed"
            col.set_label(fmt % level)
            self.ax.add_collection(col)
            collections.append(col)

        collections = silent_list('LineCollection', collections)
        # the mappable attr is for the pylab interface functions,
        # which maintain the current image
        collections.mappable = mappable
        return lev, collections
Esempio n. 8
0
    def contour(self, *args, **kwargs):
        """
        contour(self, *args, **kwargs)

        Function signatures

        contour(Z) - make a contour plot of an array Z. The level
                 values are chosen automatically.

        contour(X,Y,Z) - X,Y specify the (x,y) coordinates of the surface

        contour(Z,N) and contour(X,Y,Z,N) - draw N contour lines overriding
                         the automatic value

        contour(Z,V) and contour(X,Y,Z,V) - draw len(V) contour lines,
                       at the values specified in V (array, list, tuple)

        contour(Z, **kwargs) - Use keyword args to control colors, linewidth,
                    origin, cmap ... see below

        [L,C] = contour(...) returns a list of levels and a silent_list of LineCollections

        Z may be a masked array.

        Optional keywork args are shown with their defaults below (you must
        use kwargs for these):

            * colors = None; or one of the following:
              - a tuple of matplotlib color args (string, float, rgb, etc),
              different levels will be plotted in different colors in the order
              specified

              -  one string color, e.g. colors = 'r' or colors = 'red', all levels
              will be plotted in this color

              - if colors == None, the default colormap will be used

            * alpha=1.0 : the alpha blending value

            * cmap = None: a cm Colormap instance from matplotlib.cm.

            * origin = None: 'upper'|'lower'|'image'|None.
              If 'image', the rc value for image.origin will be used.
              If None (default), the first value of Z will correspond
              to the lower left corner, location (0,0).
              This keyword is active only if contourf is called with
              one or two arguments, that is, without explicitly
              specifying X and Y.

            * extent = None: (x0,x1,y0,y1); also active only if X and Y
              are not specified.

            * linewidths = None: or one of these:
              - a number - all levels will be plotted with this linewidth,
                e.g. linewidths = 0.6

              - a tuple of numbers, e.g. linewidths = (0.4, 0.8, 1.2) different
                levels will be plotted with different linewidths in the order
                specified

              - if linewidths == None, the default width in lines.linewidth in
                .matplotlibrc is used

            * fmt = '1.3f': a format string for adding a label to each collection.
              Useful for auto-legending.

        """

        alpha = kwargs.get('alpha', 1.0)
        linewidths = kwargs.get('linewidths', None)
        fmt = kwargs.get('fmt', '%1.3f')
        origin = kwargs.get('origin', None)
        extent = kwargs.get('extent', None)
        cmap = kwargs.get('cmap', None)
        colors = kwargs.get('colors', None)

        if cmap is not None: assert(isinstance(cmap, Colormap))
        if origin is not None: assert(origin in ['lower', 'upper', 'image'])
        if extent is not None: assert(len(extent) == 4)
        if colors is not None and cmap is not None:
            raise ValueError('Either colors or cmap must be None')
        if origin == 'image': origin = rcParams['image.origin']


        x, y, z, lev = self._contour_args(False, origin, extent, *args)

        # Manipulate the plot *after* checking the input arguments.
        if not self.ax.ishold(): self.ax.cla()

        Nlev = len(lev)
        if cmap is None:
            if colors is None:
                Ncolors = Nlev
            else:
                Ncolors = len(colors)
        else:
            Ncolors = Nlev


        tcolors, mappable, collections = self._process_colors(colors,
                                                            alpha, lev, cmap)

        if linewidths == None:
            tlinewidths = [rcParams['lines.linewidth']] *Nlev
        else:
            if iterable(linewidths) and len(linewidths) < Nlev:
                linewidths = list(linewidths) * int(ceil(Nlev/len(linewidths)))
            elif not iterable(linewidths) and type(linewidths) in [int, float]:
                linewidths = [linewidths] * Nlev
            tlinewidths = [(w,) for w in linewidths]

        C = _contour.Cntr(x, y, z.filled(), z.mask())
        for level, color, width in zip(lev, tcolors, tlinewidths):
            nlist = C.trace(level, points = 1)
            col = LineCollection(nlist)
            col.set_color(color)
            col.set_linewidth(width)

            if level < 0.0 and Ncolors == 1:
                col.set_linestyle((0, (6.,6.)),)
                #print "setting dashed"
            col.set_label(fmt%level)
            self.ax.add_collection(col)
            collections.append(col)

        collections = silent_list('LineCollection', collections)
        # the mappable attr is for the pylab interface functions,
        # which maintain the current image
        collections.mappable = mappable
        return lev, collections