コード例 #1
0
def makeMappingArray(N, data):
    """Create an N-element 1-d lookup table

    data represented by a list of x,y0,y1 mapping correspondences.
    Each element in this list represents how a value between 0 and 1
    (inclusive) represented by x is mapped to a corresponding value
    between 0 and 1 (inclusive). The two values of y are to allow
    for discontinuous mapping functions (say as might be found in a
    sawtooth) where y0 represents the value of y for values of x
    <= to that given, and y1 is the value to be used for x > than
    that given). The list must start with x=0, end with x=1, and
    all values of x must be in increasing order. Values between
    the given mapping points are determined by simple linear interpolation.

    The function returns an array "result" where result[x*(N-1)]
    gives the closest value for values of x between 0 and 1.
    """
    try:
        adata = array(data)
    except:
        raise TypeError("data must be convertable to an array")
    shape = adata.shape
    if len(shape) != 2 and shape[1] != 3:
        raise ValueError("data must be nx3 format")

    x  = adata[:,0]
    y0 = adata[:,1]
    y1 = adata[:,2]

    if x[0] != 0. or x[-1] != 1.0:
        raise ValueError(
           "data mapping points must start with x=0. and end with x=1")
    if sometrue(sort(x)-x):
        raise ValueError(
           "data mapping points must have x in increasing order")
    # begin generation of lookup table
    x = x * (N-1)
    lut = zeros((N,), Float)
    xind = arange(float(N))
    ind = searchsorted(x, xind)[1:-1]

    lut[1:-1] = ( divide(xind[1:-1] - take(x,ind-1),
                         take(x,ind)-take(x,ind-1) )
                  *(take(y0,ind)-take(y1,ind-1)) + take(y1,ind-1))
    lut[0] = y1[0]
    lut[-1] = y0[-1]
    # ensure that the lut is confined to values between 0 and 1 by clipping it
    clip(lut, 0.0, 1.0)
    #lut = where(lut > 1., 1., lut)
    #lut = where(lut < 0., 0., lut)
    return lut
コード例 #2
0
ファイル: figure.py プロジェクト: jtomase/matplotlib
def figaspect(arg):
    """
    Create a figure with specified aspect ratio.  If arg is a number,
    use that aspect ratio.  If arg is an array, figaspect will
    determine the width and height for a figure that would fit array
    preserving aspect ratio.  The figure width, height in inches are
    returned.  Be sure to create an axes with equal with and height,
    eg

    Example usage:

      # make a figure twice as tall as it is wide
      w, h = figaspect(2.)
      fig = Figure(figsize=(w,h))
      ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
      ax.imshow(A, **kwargs)


      # make a figure with the proper aspect for an array
      A = rand(5,3)
      w, h = figaspect(A)
      fig = Figure(figsize=(w,h))
      ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
      ax.imshow(A, **kwargs)

    Thanks to Fernando Perez for this function
    """

    isarray = hasattr(arg, 'shape')

    # min/max sizes to respect when autoscaling.  If John likes the idea, they
    # could become rc parameters, for now they're hardwired.
    figsize_min = array((4.0, 2.0))  # min length for width/height
    figsize_max = array((16.0, 16.0))  # max length for width/height
    #figsize_min = rcParams['figure.figsize_min']
    #figsize_max = rcParams['figure.figsize_max']

    # Extract the aspect ratio of the array
    if isarray:
        nr, nc = arg.shape[:2]
        arr_ratio = float(nr) / nc
    else:
        arr_ratio = float(arg)

    # Height of user figure defaults
    fig_height = rcParams['figure.figsize'][1]

    # New size for the figure, keeping the aspect ratio of the caller
    newsize = array((fig_height / arr_ratio, fig_height))

    # Sanity checks, don't drop either dimension below figsize_min
    newsize /= min(1.0, *(newsize / figsize_min))

    # Avoid humongous windows as well
    newsize /= max(1.0, *(newsize / figsize_max))

    # Finally, if we have a really funky aspect ratio, break it but respect
    # the min/max dimensions (we don't want figures 10 feet tall!)
    newsize = clip(newsize, figsize_min, figsize_max)
    return newsize
コード例 #3
0
ファイル: colors.py プロジェクト: jtomase/matplotlib
    def __call__(self, value):

        vmin = self.vmin
        vmax = self.vmax

        if type(value) in [IntType, FloatType]:
            vtype = 'scalar'
            val = array([value])
        else:
            vtype = 'array'
            val = asarray(value)

        # if both vmin is None and vmax is None, we'll automatically
        # norm the data to vmin/vmax of the actual data, so the
        # clipping step won't be needed.
        if vmin is None and vmax is None:
            needs_clipping = False
        else:
            needs_clipping = True

        if vmin is None or vmax is None:
            rval = ravel(val)
            if vmin is None: vmin = amin(rval)
            if vmax is None: vmax = amax(rval)
        if vmin > vmax:
            raise ValueError("minvalue must be less than or equal to maxvalue")
        elif vmin == vmax:
            return 0. * value
        else:
            if needs_clipping:
                val = clip(val, vmin, vmax)
            result = (1.0 / (vmax - vmin)) * (val - vmin)
        if vtype == 'scalar':
            result = result[0]
        return result
コード例 #4
0
 def __call__(self, value, clip=None):
     if clip is None:
         clip = self.clip
     if isinstance(value, (int, float)):
         vtype = 'scalar'
         val = ma.array([value])
     else:
         vtype = 'array'
         val = ma.asarray(value)
     self.autoscale(val)
     vmin, vmax = self.vmin, self.vmax
     if vmin > vmax:
         raise ValueError("minvalue must be less than or equal to maxvalue")
     elif vmin<=0:
         raise ValueError("values must all be positive")
     elif vmin==vmax:
         return 0.*value
     else:
         if clip:
             mask = ma.getmask(val)
             val = ma.array(nx.clip(val.filled(vmax), vmin, vmax),
                             mask=mask)
         result = (ma.log(val)-nx.log(vmin))/(nx.log(vmax)-nx.log(vmin))
     if vtype == 'scalar':
         result = result[0]
     return result
コード例 #5
0
    def __call__(self, value):

        vmin = self.vmin
        vmax = self.vmax

        if type(value) in [IntType, FloatType]:
            vtype = 'scalar'
            val = array([value])
        else:
            vtype = 'array'
            val = asarray(value)

        # if both vmin is None and vmax is None, we'll automatically
        # norm the data to vmin/vmax of the actual data, so the
        # clipping step won't be needed.
        if vmin is None and vmax is None:
            needs_clipping = False
        else:
            needs_clipping = True

        if vmin is None or vmax is None:
            rval = ravel(val)
            if vmin is None: vmin = amin(rval)
            if vmax is None: vmax = amax(rval)
        if vmin > vmax:
            raise ValueError("minvalue must be less than or equal to maxvalue")
        elif vmin==vmax:
            return 0.*value
        else:
            if needs_clipping:
                val = clip(val,vmin, vmax)
            result = (1.0/(vmax-vmin))*(val-vmin)
        if vtype == 'scalar':
            result = result[0]
        return result
コード例 #6
0
def figaspect(arg):
    """
    Create a figure with specified aspect ratio.  If arg is a number,
    use that aspect ratio.  If arg is an array, figaspect will
    determine the width and height for a figure that would fit array
    preserving aspcect ratio.  The figure width, height in inches are
    returned.  Be sure to create an axes with equal with and height,
    eg

    Example usage:

      # make a figure twice as tall as it is wide
      w, h = figaspect(2.)
      fig = Figure(figsize=(w,h))
      ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
      ax.imshow(A, **kwargs)


      # make a figure with the proper aspect for an array
      A = rand(5,3)
      w, h = figaspect(A)
      fig = Figure(figsize=(w,h))
      ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
      ax.imshow(A, **kwargs)

    Thanks to Fernando Perez for this function
    """

    isarray = hasattr(arg, "shape")

    # min/max sizes to respect when autoscaling.  If John likes the idea, they
    # could become rc parameters, for now they're hardwired.
    figsize_min = array((4.0, 2.0))  # min length for width/height
    figsize_max = array((16.0, 16.0))  # max length for width/height
    # figsize_min = rcParams['figure.figsize_min']
    # figsize_max = rcParams['figure.figsize_max']

    # Extract the aspect ratio of the array
    if isarray:
        nr, nc = arg.shape[:2]
        arr_ratio = float(nr) / nc
    else:
        arr_ratio = float(arg)

    # Height of user figure defaults
    fig_height = rcParams["figure.figsize"][1]

    # New size for the figure, keeping the aspect ratio of the caller
    newsize = array((fig_height / arr_ratio, fig_height))

    # Sanity checks, don't drop either dimension below figsize_min
    newsize /= min(1.0, *(newsize / figsize_min))

    # Avoid humongous windows as well
    newsize /= max(1.0, *(newsize / figsize_max))

    # Finally, if we have a really funky aspect ratio, break it but respect
    # the min/max dimensions (we don't want figures 10 feet tall!)
    newsize = clip(newsize, figsize_min, figsize_max)
    return newsize
コード例 #7
0
def exp_safe(x):
    """Compute exponentials which safely underflow to zero.

    Slow but convenient to use. Note that NumArray will introduce proper
    floating point exception handling with access to the underlying
    hardware."""

    if type(x) is ArrayType:
        return exp(clip(x,exp_safe_MIN,exp_safe_MAX))
    else:
        return math.exp(x)
コード例 #8
0
def exp_safe(x):
    """Compute exponentials which safely underflow to zero.

    Slow but convenient to use. Note that NumArray will introduce proper
    floating point exception handling with access to the underlying
    hardware."""

    if type(x) is ArrayType:
        return exp(clip(x, exp_safe_MIN, exp_safe_MAX))
    else:
        return math.exp(x)
コード例 #9
0
    def __call__(self, value):

        if isinstance(value, (int, float)):
            vtype = 'scalar'
            val = ma.array([value])
        else:
            vtype = 'array'
            val = ma.asarray(value)

        self.autoscale(val)
        vmin, vmax = self.vmin, self.vmax
        if vmin > vmax:
            raise ValueError("minvalue must be less than or equal to maxvalue")
        elif vmin == vmax:
            return 0. * value
        else:
            if self.clip:
                val = clip(val.filled(vmax), vmin, vmax)
            result = (val - vmin) / float(vmax - vmin)
        if vtype == 'scalar':
            result = result[0]
        return result
コード例 #10
0
    def __call__(self, value):

        if isinstance(value, (int, float)):
            vtype = 'scalar'
            val = ma.array([value])
        else:
            vtype = 'array'
            val = ma.asarray(value)

        self.autoscale(val)
        vmin, vmax = self.vmin, self.vmax
        if vmin > vmax:
            raise ValueError("minvalue must be less than or equal to maxvalue")
        elif vmin==vmax:
            return 0.*value
        else:
            if self.clip:
                val = clip(val.filled(vmax), vmin, vmax)
            result = (1.0/(vmax-vmin))*(val-vmin)
        if vtype == 'scalar':
            result = result[0]
        return result