예제 #1
0
    def SetPoints(self, points):
        """ SetPoints(points)
        
        Set x,y (and optionally z) data. The given argument can be anything
        that can be converted to a pointset. (From version 1.7 this method
        also works with 2D pointsets.)
        
        The data is copied, so changes to original data will not affect
        the visualized points. If you do want this, use the points property.
        
        """

        # Try make it a (copied) pointset (handle masked array)
        if is_Pointset(points):
            points = Pointset(handleInvalidValues(points.data))
        else:
            points = Pointset(handleInvalidValues(points))

        # Add z dimension to points if not available
        if points.ndim == 3:
            pass
        elif points.ndim == 2:
            zz = 0.1 * np.ones((len(points._data), 1), dtype='float32')
            points._data = np.concatenate((points._data, zz), 1)
        elif points.ndim == 1:
            N = len(points._data)
            xx = np.arange(N, dtype='float32').reshape(N, 1)
            zz = 0.1 * np.ones((N, 1), dtype='float32')
            points._data = np.concatenate((xx, points._data, zz), 1)

        # Store
        self._points = points
예제 #2
0
def checkDimsOfArray(value, *ndims):
    """ checkDimsOfArray(value, *ndims)
    
    Coerce value into a numpy array of size NxM, where M is in ndims.
    If 0 is in ndims, a 1D array is allowed.  Return a numpy array or
    raise a ValueError.
    
    """
    # Check if is Pointset with correct dimensionality
    if is_Pointset(value):
        if value.ndim not in ndims:
            raise ValueError()
        return value.data
    
    # Try to coerce to numpy array; raise ValueError if anything goes wrong
    if value is None:
        raise ValueError('Values for mesh is None.')
    if not isinstance(value, np.ndarray):
        try:
            value = np.array(value, dtype=np.float32)
        except Exception:
            raise ValueError('Could not coerce to numpy array.')
    
    # Allow 1D?
    if value.ndim==1 and 0 in ndims:
        value = value.reshape(value.size,1) # reshape gives view on same data
    
    # value is guaranteed to be a numpy array here; check dimensionality
    if not value.ndim == 2 and value.shape[1] in ndims:
        raise ValueError()
    if value.dtype == np.float32:
        return value
    else:
        return value.astype(np.float32)
예제 #3
0
def checkDimsOfArray(value, *ndims):
    """ checkDimsOfArray(value, *ndims)
    
    Coerce value into a numpy array of size NxM, where M is in ndims.
    If 0 is in ndims, a 1D array is allowed.  Return a numpy array or
    raise a ValueError.
    
    """
    # Check if is Pointset with correct dimensionality
    if is_Pointset(value):
        if value.ndim not in ndims:
            raise ValueError()
        return value.data
    
    # Try to coerce to numpy array; raise ValueError if anything goes wrong
    if value is None:
        raise ValueError('Values for mesh is None.')
    if not isinstance(value, np.ndarray):
        try:
            value = np.array(value, dtype=np.float32)
        except Exception:
            raise ValueError('Could not coerce to numpy array.')
    
    # Allow 1D?
    if value.ndim==1 and 0 in ndims:
        value = value.reshape(value.size,1) # reshape gives view on same data
    
    # value is guaranteed to be a numpy array here; check dimensionality
    if not value.ndim == 2 and value.shape[1] in ndims:
        raise ValueError()
    if value.dtype == np.float32:
        return value
    else:
        return value.astype(np.float32)
예제 #4
0
파일: line.py 프로젝트: turapeach/TOAK
 def SetPoints(self, points):
     """ SetPoints(points)
     
     Set x,y (and optionally z) data. The given argument can be anything
     that can be converted to a pointset. (From version 1.7 this method
     also works with 2D pointsets.)
     
     The data is copied, so changes to original data will not affect 
     the visualized points. If you do want this, use the points property.
     
     """
     
     # Try make it a (copied) pointset (handle masked array)
     if is_Pointset(points):
         points = Pointset(handleInvalidValues(points.data))
     else:
         points = Pointset(handleInvalidValues(points))
    
     # Add z dimension to points if not available
     if points.ndim == 2:
         tmp = points._data, 0.1*np.ones((len(points._data),1), dtype='float32')
         points._data = np.concatenate(tmp,1)
     
     # Store
     self._points = points
예제 #5
0
def solidLine(pp, radius=1.0, N=16, axesAdjust=True, axes=None):
    """ solidLine(pp, radius=1.0, N=16, axesAdjust=True, axes=None)
    
    Creates a solid line in 3D space.
    
    Parameters
    ----------
    Note that translation, scaling, and direction can also be given
    using a Point instance.
    pp : Pointset
        The sequence of points of which the line consists.
    radius : scalar or sequence
        The radius of the line to create. If a sequence if given, it
        specifies the radius for each point in pp.
    N : int
        The number of subdivisions around its centerline. If smaller
        than 8, flat shading is used instead of smooth shading.
    axesAdjust : bool
        If True, this function will call axes.SetLimits(), and set
        the camera type to 3D. If daspectAuto has not been set yet,
        it is set to False.
    axes : Axes instance
        Display the bars in the given axes, or the current axes if not given.
    
    """
    
    # Check first argument
    if is_Pointset(pp):
        pass
    else:
        raise ValueError('solidLine() needs a Pointset or list of pointsets.')
    
    # Obtain mesh and make a visualization mesh
    baseMesh = lineToMesh(pp, radius, N)
    
    
    ## Visualize
    
    # Get axes
    if axes is None:
        axes = vv.gca()
    
    # Create mesh object
    m = vv.Mesh(axes, baseMesh)
    
    # Adjust axes
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = False
        axes.cameraType = '3d'
        axes.SetLimits()
    
    # Return
    axes.Draw()
    return m
예제 #6
0
def solidLine(pp, radius=1.0, N=16, axesAdjust=True, axes=None):
    """ solidLine(pp, radius=1.0, N=16, axesAdjust=True, axes=None)
    
    Creates a solid line in 3D space. 
    
    Parameters
    ----------
    Note that translation, scaling, and direction can also be given
    using a Point instance.
    pp : Pointset
        The sequence of points of which the line consists.
    radius : scalar or sequence
        The radius of the line to create. If a sequence if given, it 
        specifies the radius for each point in pp.
    N : int
        The number of subdivisions around its centerline. If smaller
        than 8, flat shading is used instead of smooth shading. 
    axesAdjust : bool
        If True, this function will call axes.SetLimits(), and set
        the camera type to 3D. If daspectAuto has not been set yet, 
        it is set to False.
    axes : Axes instance
        Display the bars in the given axes, or the current axes if not given.
    
    """
    
    # Check first argument
    if is_Pointset(pp):
        pass
    else:
        raise ValueError('solidLine() needs a Pointset or list of pointsets.')
    
    # Obtain mesh and make a visualization mesh
    baseMesh = lineToMesh(pp, radius, N)
    
    
    ## Visualize
    
    # Get axes
    if axes is None:
        axes = vv.gca()
    
    # Create mesh object
    m = vv.Mesh(axes, baseMesh)
    
    # Adjust axes
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = False
        axes.cameraType = '3d'
        axes.SetLimits()
    
    # Return
    axes.Draw()
    return m
예제 #7
0
파일: plot.py 프로젝트: turapeach/TOAK
def plot(data1, data2=None, data3=None, 
            lw=1, lc='b', ls="-", mw=7, mc='b', ms='', mew=1, mec='k', 
            alpha=1, axesAdjust=True, axes=None, **kwargs):
    """ plot(*args, lw=1, lc='b', ls="-", mw=7, mc='b', ms='', mew=1, mec='k', 
            alpha=1, axesAdjust=True, axes=None):
    
    Plot 1, 2 or 3 dimensional data and return the Line object.
    
    Usage
    -----
      * plot(Y, ...) plots a 1D signal, with the values plotted along the y-axis
      * plot(X, Y, ...) also supplies x coordinates
      * plot(X, Y, Z, ...) also supplies z coordinates
      * plot(P, ...) plots using a Point or Pointset instance
    
    Keyword arguments
    -----------------
    (The longer names for the line properties can also be used)    
    lw : scalar
        lineWidth. The width of the line. If zero, no line is drawn.
    mw : scalar
        markerWidth. The width of the marker. If zero, no marker is drawn.
    mew : scalar
        markerEdgeWidth. The width of the edge of the marker.    
    lc : 3-element tuple or char
        lineColor. The color of the line. A tuple should represent the RGB
        values between 0 and 1. If a char is given it must be
        one of 'rgbmcywk', for reg, green, blue, magenta, cyan, yellow, 
        white, black, respectively.
    mc : 3-element tuple or char
        markerColor. The color of the marker. See lineColor.
    mec : 3-element tuple or char
        markerEdgeColor. The color of the edge of the marker.    
    ls : string
        lineStyle. The style of the line. (See below)
    ms : string
        markerStyle. The style of the marker. (See below)
    axesAdjust : bool
        If axesAdjust==True, this function will call axes.SetLimits(), set
        the camera type to 2D when plotting 2D data and to 3D when plotting
        3D data. If daspectAuto has not been set yet, it is set to True.
    axes : Axes instance
        Display the image in this axes, or the current axes if not given.
    
    Line styles
    -----------
      * Solid line: '-'
      * Dotted line: ':'
      * Dashed line: '--'
      * Dash-dot line: '-.' or '.-'
      * A line that is drawn between each pair of points: '+'
      * No line: '' or None.
    
    Marker styles
    -------------
      * Plus: '+'
      * Cross: 'x'
      * Square: 's'
      * Diamond: 'd'
      * Triangle (pointing up, down, left, right): '^', 'v', '<', '>'
      * Pentagram star: 'p' or '*'
      * Hexgram: 'h'
      * Point/cirle: 'o' or '.'
      * No marker: '' or None
    
    """
    
    # create a dict from the properties and combine with kwargs
    tmp     = { 'lineWidth':lw,         'lineColor':lc,     'lineStyle':ls,
                'markerWidth':mw,       'markerColor':mc,   'markerStyle':ms,
                'markerEdgeWidth':mew,  'markerEdgeColor':mec}
    for i in tmp:
        if not i in kwargs:
            kwargs[i] = tmp[i]
    
    # init dimension variable
    camDim = 0
    
    ##  create the data
    
    if is_Pointset(data1):
        pp = data1
    elif is_Point(data1):
        pp = Pointset(data1.ndim)
        pp.append(data1)
    else:   
        
        if data1 is None:
            raise Exception("The first argument cannot be None!")
        data1 = np.asanyarray(data1)
        
        d3 = data3
        if data3 is None:
            data3 = 0.1*np.ones(data1.shape)
            camDim = 2
        else:
            camDim = 3
            data3 = np.asanyarray(data3)
        
        if data2 is None:
            if d3 is not None:
                tmp = "third argument in plot() ignored, as second not given."
                print("Warning: " + tmp)
            # y data is given, xdata must be a range starting from 1
            data2 = data1
            data1 = np.arange(1,data2.shape[0]+1)
            data3 = 0.1*np.ones(data2.shape)
        else:
            data2 = np.asanyarray(data2)
        
        # check dimensions
        L = data1.size
        if L != data2.size or L != data3.size:
            raise Exception("Array dimensions do not match! %i vs %i vs %i" % 
                    (data1.size, data2.size, data3.size))
        
        # build points
        data1 = data1.reshape((data1.size,1))
        data2 = data2.reshape((data2.size,1))
        data3 = data3.reshape((data3.size,1))
        
        # Concatenate to a single Nx3 array (take care of masked arrays)
        tmp = data1, data2, data3
        if any([isinstance(d, np.ma.MaskedArray) for d in tmp]):
            pp = np.ma.concatenate(tmp, 1)
        else:
            pp = np.concatenate(tmp, 1)
        
    
    # Process camdim for given points or pointsets
    if not camDim:
        camDim = pp.ndim
        
    
    ## create the line
    if axes is None:
        axes = vv.gca()    
    l = vv.Line(axes, pp)
    l.lw = kwargs['lineWidth']
    l.lc = kwargs['lineColor']
    l.ls = kwargs['lineStyle']
    l.mw = kwargs['markerWidth'] 
    l.mc = kwargs['markerColor'] 
    l.ms = kwargs['markerStyle']
    l.mew = kwargs['markerEdgeWidth']
    l.mec = kwargs['markerEdgeColor']
    l.alpha = alpha
    
    ## done...
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = True
        axes.cameraType = str(camDim)+'d'
        axes.SetLimits()
    
    axes.Draw()
    return l
예제 #8
0
def plot(data1, data2=None, data3=None,
            lw=1, lc='b', ls="-", mw=7, mc='b', ms='', mew=1, mec='k',
            alpha=1, axesAdjust=True, axes=None, **kwargs):
    """ plot(*args, lw=1, lc='b', ls="-", mw=7, mc='b', ms='', mew=1, mec='k',
            alpha=1, axesAdjust=True, axes=None):
    
    Plot 1, 2 or 3 dimensional data and return the Line object.
    
    Usage
    -----
      * plot(Y, ...) plots a 1D signal, with the values plotted along the y-axis
      * plot(X, Y, ...) also supplies x coordinates
      * plot(X, Y, Z, ...) also supplies z coordinates
      * plot(P, ...) plots using a Point or Pointset instance
    
    Keyword arguments
    -----------------
    (The longer names for the line properties can also be used)
    lw : scalar
        lineWidth. The width of the line. If zero, no line is drawn.
    mw : scalar
        markerWidth. The width of the marker. If zero, no marker is drawn.
    mew : scalar
        markerEdgeWidth. The width of the edge of the marker.
    lc : 3-element tuple or char
        lineColor. The color of the line. A tuple should represent the RGB
        values between 0 and 1. If a char is given it must be
        one of 'rgbmcywk', for reg, green, blue, magenta, cyan, yellow,
        white, black, respectively.
    mc : 3-element tuple or char
        markerColor. The color of the marker. See lineColor.
    mec : 3-element tuple or char
        markerEdgeColor. The color of the edge of the marker.
    ls : string
        lineStyle. The style of the line. (See below)
    ms : string
        markerStyle. The style of the marker. (See below)
    axesAdjust : bool
        If axesAdjust==True, this function will call axes.SetLimits(), set
        the camera type to 2D when plotting 2D data and to 3D when plotting
        3D data. If daspectAuto has not been set yet, it is set to True.
    axes : Axes instance
        Display the image in this axes, or the current axes if not given.
    
    Line styles
    -----------
      * Solid line: '-'
      * Dotted line: ':'
      * Dashed line: '--'
      * Dash-dot line: '-.' or '.-'
      * A line that is drawn between each pair of points: '+'
      * No line: '' or None.
    
    Marker styles
    -------------
      * Plus: '+'
      * Cross: 'x'
      * Square: 's'
      * Diamond: 'd'
      * Triangle (pointing up, down, left, right): '^', 'v', '<', '>'
      * Pentagram star: 'p' or '*'
      * Hexgram: 'h'
      * Point/cirle: 'o' or '.'
      * No marker: '' or None
    
    """
    
    # create a dict from the properties and combine with kwargs
    tmp     = { 'lineWidth':lw,         'lineColor':lc,     'lineStyle':ls,
                'markerWidth':mw,       'markerColor':mc,   'markerStyle':ms,
                'markerEdgeWidth':mew,  'markerEdgeColor':mec}
    for i in tmp:
        if not i in kwargs:
            kwargs[i] = tmp[i]
    
    # init dimension variable
    camDim = 0
    
    ##  create the data
    
    # If one argument is given, and it looks like a pointset stored
    # in a numpy array, use it as such
    if isinstance(data1, np.ndarray) and (data2 is None) and (data3 is None):
        if data1.ndim == 2 and data1.shape[1] in (2,3):
            data1 = Pointset(data1)  # Use shape as given
    
    if is_Pointset(data1):
        pp = data1
    elif is_Point(data1):
        pp = Pointset(data1.ndim)
        pp.append(data1)
    else:
        if data1 is None:
            raise Exception("The first argument cannot be None!")
        data1 = np.asanyarray(data1)
        
        d3 = data3
        if data3 is None:
            data3 = 0.1*np.ones(data1.shape)
            camDim = 2
        else:
            camDim = 3
            data3 = np.asanyarray(data3)
        
        if data2 is None:
            if d3 is not None:
                tmp = "third argument in plot() ignored, as second not given."
                print("Warning: " + tmp)
            # y data is given, xdata must be a range starting from 1
            data2 = data1
            data1 = np.arange(1,data2.shape[0]+1)
            data3 = 0.1*np.ones(data2.shape)
        else:
            data2 = np.asanyarray(data2)
        
        # check dimensions
        L = data1.size
        if L != data2.size or L != data3.size:
            raise Exception("Array dimensions do not match! %i vs %i vs %i" %
                    (data1.size, data2.size, data3.size))
        
        # build points
        data1 = data1.reshape((data1.size,1))
        data2 = data2.reshape((data2.size,1))
        data3 = data3.reshape((data3.size,1))
        
        # Concatenate to a single Nx3 array (take care of masked arrays)
        tmp = data1, data2, data3
        if any([isinstance(d, np.ma.MaskedArray) for d in tmp]):
            pp = np.ma.concatenate(tmp, 1)
        else:
            pp = np.concatenate(tmp, 1)
        
    
    # Process camdim for given points or pointsets
    if not camDim:
        camDim = max(2, pp.ndim)
        
    
    ## create the line
    if axes is None:
        axes = vv.gca()
    l = vv.Line(axes, pp)
    l.lw = kwargs['lineWidth']
    l.lc = kwargs['lineColor']
    l.ls = kwargs['lineStyle']
    l.mw = kwargs['markerWidth']
    l.mc = kwargs['markerColor']
    l.ms = kwargs['markerStyle']
    l.mew = kwargs['markerEdgeWidth']
    l.mec = kwargs['markerEdgeColor']
    l.alpha = alpha
    
    ## done...
    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = True
        axes.cameraType = str(camDim)+'d'
        axes.SetLimits()
    
    axes.Draw()
    return l
예제 #9
0
파일: polarplot.py 프로젝트: chiluf/visvis
def polarplot(data1,
              data2=None,
              inRadians=False,
              lw=1,
              lc='b',
              ls="-",
              mw=7,
              mc='b',
              ms='',
              mew=1,
              mec='k',
              alpha=1,
              axesAdjust=True,
              axes=None,
              **kwargs):
    """ polarplot(*args, inRadians=False,
            lw=1, lc='b', ls="-", mw=7, mc='b', ms='', mew=1, mec='k',
            alpha=1, axesAdjust=True, axes=None):
    
    Plot 2D polar data, using a polar axis to draw a polar grid. 
    
    Usage
    -----
      * plot(Y, ...) plots a 1D polar signal.
      * plot(X, Y, ...) also supplies angular coordinates
      * plot(P, ...) plots using a Point or Pointset instance
    
    Keyword arguments
    -----------------
    (The longer names for the line properties can also be used)    
    lw : scalar
        lineWidth. The width of the line. If zero, no line is drawn.
    mw : scalar
        markerWidth. The width of the marker. If zero, no marker is drawn.
    mew : scalar
        markerEdgeWidth. The width of the edge of the marker.    
    lc : 3-element tuple or char
        lineColor. The color of the line. A tuple should represent the RGB
        values between 0 and 1. If a char is given it must be
        one of 'rgbmcywk', for reg, green, blue, magenta, cyan, yellow, 
        white, black, respectively.
    mc : 3-element tuple or char
        markerColor. The color of the marker. See lineColor.
    mec : 3-element tuple or char
        markerEdgeColor. The color of the edge of the marker.    
    ls : string
        lineStyle. The style of the line. (See below)
    ms : string
        markerStyle. The style of the marker. (See below)
    axesAdjust : bool
        If axesAdjust==True, this function will call axes.SetLimits(), and set
        the camera type to 2D. 
    axes : Axes instance
        Display the image in this axes, or the current axes if not given.
    
    Line styles
    -----------
      * Solid line: '-'
      * Dotted line: ':'
      * Dashed line: '--'
      * Dash-dot line: '-.' or '.-'
      * A line that is drawn between each pair of points: '+'
      * No line: '' or None.
    
    Marker styles
    -------------
      * Plus: '+'
      * Cross: 'x'
      * Square: 's'
      * Diamond: 'd'
      * Triangle (pointing up, down, left, right): '^', 'v', '<', '>'
      * Pentagram star: 'p' or '*'
      * Hexgram: 'h'
      * Point/cirle: 'o' or '.'
      * No marker: '' or None
    
    Polar axis
    ----------
    This polar axis has a few specialized methods for adjusting the polar
    plot. Access these via vv.gca().axis.    
      * SetLimits(thetaRange, radialRange)
      * thetaRange, radialRange = GetLimits()
      * angularRefPos: Get and Set methods for the relative screen
        angle of the 0 degree polar reference.  Default is 0 degs
        which corresponds to the positive x-axis (y =0)
      * isCW: Get and Set methods for the sense of rotation CCW or
        CW. This method takes/returns a bool (True if the default CW).
    
    Interaction
    -----------
      * Drag mouse up/down to translate radial axis.    
      * Drag mouse left/right to rotate angular ref position.    
      * Drag mouse + shift key up/down to rescale radial axis (min R fixed).
    
    """

    # create a dict from the properties and combine with kwargs
    tmp = {
        'lineWidth': lw,
        'lineColor': lc,
        'lineStyle': ls,
        'markerWidth': mw,
        'markerColor': mc,
        'markerStyle': ms,
        'markerEdgeWidth': mew,
        'markerEdgeColor': mec
    }
    for i in tmp:
        if not i in kwargs:
            kwargs[i] = tmp[i]

    ##  create the data
    if is_Pointset(data1):
        pp = data1
    elif is_Point(data1):
        pp = Pointset(data1.ndim)
        pp.append(data1)
    else:

        if data1 is None:
            raise ValueError("The first argument cannot be None!")
        data1 = makeArray(data1)

        if data2 is None:
            # R data is given, thetadata must be
            # a range starting from 0 degrees
            data2 = data1
            data1 = np.arange(0, data2.shape[0])
        else:
            data2 = makeArray(data2)

        # check dimensions
        L = data1.size
        if L != data2.size:
            raise ValueError("Array dimensions do not match! %i vs %i " %
                             (data1.size, data2.size))

        # build points
        data1 = data1.reshape((data1.size, 1))
        data2 = data2.reshape((data2.size, 1))

    if not inRadians:
        data1 = np.pi * data1 / 180.0

    ## create the line
    if axes is None:
        axes = vv.gca()
    axes.axisType = 'polar'
    fig = axes.GetFigure()

    l = PolarLine(axes, data1, data2)
    l.lw = kwargs['lineWidth']
    l.lc = kwargs['lineColor']
    l.ls = kwargs['lineStyle']
    l.mw = kwargs['markerWidth']
    l.mc = kwargs['markerColor']
    l.ms = kwargs['markerStyle']
    l.mew = kwargs['markerEdgeWidth']
    l.mec = kwargs['markerEdgeColor']
    l.alpha = alpha

    ## almost done...

    # Init axis
    #     axes.axis.SetLimits()

    if axesAdjust:
        if axes.daspectAuto is None:
            axes.daspectAuto = True
        axes.cameraType = '2d'
        axes.SetLimits()

    # Subsribe after-draw event handler
    # (unsubscribe first in case we do multiple plots)
    fig.eventAfterDraw.Unbind(_SetLimitsAfterDraw)
    fig.eventAfterDraw.Bind(_SetLimitsAfterDraw)

    # Return
    axes.Draw()
    return l