예제 #1
0
 def fset(self, value):
     if isinstance(value, (list, tuple)) and len(value) == 3:                
         self._translateTransform.dx = value[0]
         self._translateTransform.dy = value[1]
         self._translateTransform.dz = value[2]
     elif is_Point(value) and value.ndim == 3:
         self._translateTransform.dx = value.x
         self._translateTransform.dy = value.y
         self._translateTransform.dz = value.z
     else:
         raise ValueError('Translation should be a 3D Point or 3-element tuple.')
예제 #2
0
 def fset(self, value):
     if isinstance(value, (list, tuple)) and len(value) == 3:
         self._translateTransform.dx = value[0]
         self._translateTransform.dy = value[1]
         self._translateTransform.dz = value[2]
     elif is_Point(value) and value.ndim == 3:
         self._translateTransform.dx = value.x
         self._translateTransform.dy = value.y
         self._translateTransform.dz = value.z
     else:
         raise ValueError(
             'Translation should be a 3D Point or 3-element tuple.')
예제 #3
0
 def fset(self, value):
     if isinstance(value, (float, int)):
         self._scaleTransform.sx = float(value)
         self._scaleTransform.sy = float(value)
         self._scaleTransform.sz = float(value)
     elif isinstance(value, (list, tuple)) and len(value) == 3:                
         self._scaleTransform.sx = float(value[0])
         self._scaleTransform.sy = float(value[1])
         self._scaleTransform.sz = float(value[2])
     elif is_Point(value) and value.ndim == 3:
         self._scaleTransform.sx = value.x
         self._scaleTransform.sy = value.y
         self._scaleTransform.sz = value.z
     else:
         raise ValueError('Scaling should be a scalar, 3D Point, or 3-element tuple.')
예제 #4
0
 def fset(self, value):
     if isinstance(value, (float, int)):
         self._scaleTransform.sx = float(value)
         self._scaleTransform.sy = float(value)
         self._scaleTransform.sz = float(value)
     elif isinstance(value, (list, tuple)) and len(value) == 3:
         self._scaleTransform.sx = float(value[0])
         self._scaleTransform.sy = float(value[1])
         self._scaleTransform.sz = float(value[2])
     elif is_Point(value) and value.ndim == 3:
         self._scaleTransform.sx = value.x
         self._scaleTransform.sy = value.y
         self._scaleTransform.sz = value.z
     else:
         raise ValueError(
             'Scaling should be a scalar, 3D Point, or 3-element tuple.'
         )
예제 #5
0
파일: base.py 프로젝트: chiluf/visvis
    def TransformPoint(self, p, baseWobject=None):
        """ TransformPoint(p, baseWobject=None)
        
        Transform a point in the local coordinate system of this wobject
        to the coordinate system of the given baseWobject (which should be
        a parent of this wobject), or to the global (Axes) coordinate 
        system if not given.
        
        This is done by taking into account the transformations applied
        to this wobject and its parent wobjects.
        
        If baseWobject is the current wobject itself, only the tranformations
        of this wobject are applied.
        
        """
        if not (is_Point(p) and p.ndim == 3):
            raise ValueError('TransformPoint only accepts a 3D point')

        # Init wobject as itself. Next round it will be its parent, etc.
        wobject = self

        # Iterate over wobjects until we reach the Axes or None
        while isinstance(wobject, Wobject):
            # Iterate over all transformations
            for t in reversed(wobject._transformations):
                if isinstance(t, Transform_Translate):
                    p.x += t.dx
                    p.y += t.dy
                    p.z += t.dz
                elif isinstance(t, Transform_Scale):
                    p.x *= t.sx
                    p.y *= t.sy
                    p.z *= t.sz
                elif isinstance(t, Transform_Rotate):
                    angle = float(t.angle * np.pi / 180.0)
                    q = Quaternion.create_from_axis_angle(
                        angle, t.ax, t.ay, t.az)
                    p = q.rotate_point(p)
            # Done or move to next parent?
            if wobject is baseWobject:
                break
            else:
                wobject = wobject.parent

        # Done
        return p
예제 #6
0
 def TransformPoint(self, p, baseWobject=None):
     """ TransformPoint(p, baseWobject=None)
     
     Transform a point in the local coordinate system of this wobject
     to the coordinate system of the given baseWobject (which should be
     a parent of this wobject), or to the global (Axes) coordinate 
     system if not given.
     
     This is done by taking into account the transformations applied
     to this wobject and its parent wobjects.
     
     If baseWobject is the current wobject itself, only the tranformations
     of this wobject are applied.
     
     """
     if not (is_Point(p) and p.ndim==3):
         raise ValueError('TransformPoint only accepts a 3D point')
     
     # Init wobject as itself. Next round it will be its parent, etc.
     wobject = self
     
     # Iterate over wobjects until we reach the Axes or None
     while isinstance(wobject, Wobject):
         # Iterate over all transformations
         for t in reversed(wobject._transformations):
             if isinstance(t, Transform_Translate):
                 p.x += t.dx
                 p.y += t.dy
                 p.z += t.dz
             elif isinstance(t, Transform_Scale):
                 p.x *= t.sx
                 p.y *= t.sy
                 p.z *= t.sz
             elif isinstance(t, Transform_Rotate):
                 angle = float(t.angle * np.pi / 180.0)
                 q = Quaternion.create_from_axis_angle(angle, t.ax, t.ay, t.az)
                 p = q.rotate_point(p)
         # Done or move to next parent?
         if wobject is baseWobject:
             break
         else:
             wobject = wobject.parent
     
     # Done
     return p
예제 #7
0
        def fset(self, value):
            # Store direction
            if isinstance(value, (list, tuple)) and len(value) == 3:
                self._direction = Point(*tuple(value))
            elif is_Point(value) and value.ndim == 3:
                self._direction = value
            else:
                raise ValueError(
                    'Direction should be a 3D Point or 3-element tuple.')

            # Normalize
            if self._direction.norm() == 0:
                raise ValueError(
                    'Direction vector must have a non-zero length.')
            self._direction = self._direction.normalize()

            # Create ref point
            refPoint = self._refDirection

            # Convert to rotation. The cross product of two vectors results
            # in a vector normal to both vectors. This is the axis of rotation
            # over which the minimal rotation is achieved.
            axis = self._direction.cross(refPoint)
            if axis.norm() < 0.01:
                if self._direction.z > 0:
                    # No rotation
                    self._directionTransform.ax = 0.0
                    self._directionTransform.ay = 0.0
                    self._directionTransform.az = 1.0
                    self._directionTransform.angle = 0.0
                else:
                    # Flipped
                    self._directionTransform.ax = 1.0
                    self._directionTransform.ay = 0.0
                    self._directionTransform.az = 0.0
                    self._directionTransform.angle = 180.0
            else:
                axis = axis.normalize()
                angle = -refPoint.angle(self._direction)
                self._directionTransform.ax = axis.x
                self._directionTransform.ay = axis.y
                self._directionTransform.az = axis.z
                self._directionTransform.angle = angle * 180 / np.pi
예제 #8
0
 def fset(self, value):
     # Store direction
     if isinstance(value, (list, tuple)) and len(value) == 3:
         self._direction = Point(*tuple(value))
     elif is_Point(value) and value.ndim == 3:
         self._direction = value
     else:
         raise ValueError('Direction should be a 3D Point or 3-element tuple.')
     
     # Normalize
     if self._direction.norm()==0:
         raise ValueError('Direction vector must have a non-zero length.')            
     self._direction = self._direction.normalize()
     
     # Create ref point
     refPoint = self._refDirection
     
     # Convert to rotation. The cross product of two vectors results
     # in a vector normal to both vectors. This is the axis of rotation
     # over which the minimal rotation is achieved.
     axis = self._direction.cross(refPoint)
     if axis.norm() < 0.01:
         if self._direction.z > 0:
             # No rotation
             self._directionTransform.ax = 0.0
             self._directionTransform.ay = 0.0
             self._directionTransform.az = 1.0
             self._directionTransform.angle = 0.0
         else:
             # Flipped
             self._directionTransform.ax = 1.0
             self._directionTransform.ay = 0.0
             self._directionTransform.az = 0.0
             self._directionTransform.angle = 180.0
     else:
         axis = axis.normalize()
         angle = -refPoint.angle(self._direction)
         self._directionTransform.ax = axis.x
         self._directionTransform.ay = axis.y
         self._directionTransform.az = axis.z
         self._directionTransform.angle = angle * 180 / np.pi
예제 #9
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
예제 #10
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
예제 #11
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