Example #1
0
def compareGraphsVisually(graph1, graph2, fig=None):
    """ compareGraphsVisually(graph1, graph2, fig=None)
    Show the two graphs together in a figure. Matched nodes are
    indicated by lines between them.
    """
    
    # Get figure
    if isinstance(fig,int):
        fig = vv.figure(fig)
    elif fig is None:
        fig = vv.figure()
    
    # Prepare figure and axes
    fig.Clear()
    a = vv.gca()
    a.cameraType = '3d'; a.daspectAuto = False
    
    # Draw both graphs
    graph1.Draw(lc='b', mc='b')
    graph2.Draw(lc='r', mc='r')
    
    # Set the limits
    a.SetLimits()
    
    # Make a line from the edges
    pp = Pointset(3)
    for node in graph1:
        if hasattr(node, 'match') and node.match is not None:
            pp.append(node); pp.append(node.match)
    
    # Plot edges
    vv.plot(pp, lc='g', ls='+')
Example #2
0
    def test_gui(self):
        pp = Pointset(3)
        pp.append(0, 0, 0)
        pp.append(0, 1, 0)
        pp.append(1, 2, 0)
        pp.append(0, 2, 1)

        # Create all solids
        vv.solidBox((0, 0, 0))
        sphere = vv.solidSphere((3, 0, 0))
        cone = vv.solidCone((6, 0, 0))
        # a cone with 4 faces is a pyramid
        pyramid = vv.solidCone((9, 0, 0), N=4)
        vv.solidCylinder((0, 3, 0), (1, 1, 2))
        ring = vv.solidRing((3, 3, 0))
        vv.solidTeapot((6, 3, 0))
        vv.solidLine(pp+Point(9, 3, 0), radius=0.2)

        # Make the ring green
        ring.faceColor = 'g'

        # Make the sphere dull
        sphere.specular = 0
        sphere.diffuse = 0.4

        # Show lines in yellow pyramid
        pyramid.faceColor = 'r'
        pyramid.edgeShading = 'plain'

        # Colormap example
        N = cone._vertices.shape[0]
        cone.SetValues(np.linspace(0, 1, N))
        cone.colormap = vv.CM_JET
Example #3
0
    def OnDown(self, event):
        """ Called when the mouse is pressed down in the axes.
        """

        # Only process left mouse button
        if event.button != 1:
            return False

        # Store location
        self._active = Point(event.x2d, event.y2d)

        # Clear temp line object
        if self._line1:
            self._line1.Destroy()

        # Create line objects
        tmp = Pointset(2)
        tmp.append(self._active)
        tmp.append(self._active)
        self._line1 = vv.plot(tmp, lc="r", lw="1", axes=self._a, axesAdjust=0)

        # Draw
        self._a.Draw()

        # Prevent dragging by indicating the event needs no further handling
        return True
Example #4
0
 def Pack(self):
     """ Pack()
     Pack the contents in an ssdf struct, such that it can be stored.
     """
     
     # If nodelist is empty, ndim defaults to two
     ndim = 2
     
     # Get a list of all edges
     cc = self.GetEdges()
     
     # Check whether the nodes are homogenous, otherwise we cannot store
     if len(self):
         ndim = self[0].ndim
         for node in self:
             if not node.ndim == ndim:
                 raise ValueError('All nodes should have the same dimension.')
     
     # Init struct
     struct = ssdf.new()
     
     # Create array of nodes        
     pp = Pointset(ndim)
     for node in self:
         pp.append(node)
     struct.nodes = pp.data
     
     # Create the edges
     tmp = np.zeros((len(cc), 2), dtype=np.uint32)
     for i in range(len(cc)):
         c = cc[i]            
         tmp[i,0] = c._i1
         tmp[i,1] = c._i2
     struct.edges = tmp
     
     
     # Store the properties of the edges. The propRefs array
     # Does contain redundant data, but it can be stored efficiently
     # because the compression handles that...
     allProps = ''
     propRefs = np.zeros((len(cc), 2), dtype=np.uint32)
     for i in range(len(cc)):
         tmp = serializeProps(cc[i].props)
         propRefs[i, 0] = len(allProps)
         propRefs[i, 1] = len(allProps) + len(tmp)
         allProps += tmp
     struct.edgePropRefs = propRefs
     if allProps:
         struct.edgeProps = np.frombuffer( allProps, dtype=np.uint8)
     else:
         struct.edgeProps = np.zeros( (0,), dtype=np.uint8)
     
     # done
     return struct
Example #5
0
    def OnMotion(self, event):
        """ Called when the mouse is moved in the axes.
        """

        if self._active and self._line1:
            # Update line
            tmp = Pointset(2)
            tmp.append(self._active)
            tmp.append(event.x2d, event.y2d)
            self._line1.SetPoints(tmp)
            # Draw
            self._a.Draw()
Example #6
0
    def __init__(self):

        # Create figure and axes
        vv.figure()
        self._a = a = vv.gca()
        vv.title("Hold mouse to draw lines. Use 'rgbcmyk' and '1-9' keys.")

        # Set axes
        a.SetLimits((0, 1), (0, 1))
        a.cameraType = "2d"
        a.daspectAuto = False
        a.axis.showGrid = True

        # Init variables needed during drawing
        self._active = None
        self._pp = Pointset(2)

        # Create null and empty line objects
        self._line1 = None
        self._line2 = vv.plot(vv.Pointset(2), ls="+", lc="c", lw="2", axes=a)

        # Bind to events
        a.eventMouseDown.Bind(self.OnDown)
        a.eventMouseUp.Bind(self.OnUp)
        a.eventMotion.Bind(self.OnMotion)
        a.eventKeyDown.Bind(self.OnKey)
Example #7
0
 def Draw(self, mc='g', lc='y', mw=7, lw=0.6, alpha=0.5, axes=None):
     """ Draw(mc='g', lc='y', mw=7, lw=0.6, alpha=0.5, axes=None)
     Draw nodes and edges. 
     """ 
     
     # We can only draw if we have any nodes
     if not len(self):
         return
     
     # Make sure there are elements in the lines list
     while len(self._lines)<2:
         self._lines.append(None)
     
     # Build node list
     if mc and mw:
         pp = Pointset(self[0].ndim)
         for p in self:
             pp.append(p)
         # Draw nodes, reuse if possible!
         l_node = self._lines[0]            
         if l_node and len(l_node._points) == len(pp):
             l_node.SetPoints(pp)
         elif l_node:
             l_node.Destroy()
             l_node = None
         if l_node is None:                
             l_node = vv.plot(pp, ls='', ms='o', mc=mc, mw=mw, 
                 axesAdjust=0, axes=axes, alpha=alpha)
             self._lines[0] = l_node
     
     # For simplicity, always redraw edges
     if self._lines[1] is not None: 
         self._lines[1].Destroy()
     
     # Build edge list
     if lc and lw:
         cc = self.GetEdges()
         # Draw edges
         pp = Pointset(self[0].ndim)
         for c in cc:            
             pp.append(c.end1); pp.append(c.end2)
         tmp = vv.plot(pp, ms='', ls='+', lc=lc, lw=lw, 
             axesAdjust=0, axes=axes, alpha=alpha)
         self._lines[1] = tmp
Example #8
0
def compareGraphs(graph1, graph2, maxDist):
    """ compareGraphs(graph1, graph2, maxDist)
    Compare two graphs to produce a matching score. Returns a MatchingScore
    instance.
    
    Matching and not-matching edges are counted to obtain a matching
    score. nodes should be closer than maxDist to be considered 'at the 
    same location'.
    """
    
    # Check graphs
    if not graph1 or not graph2:
        print('Warning: one of the graphs to compare is empty.')
        return MatchingScore(0,1,0)
        #raise ValueError('One of the graphs to compare is empty.')
    
    # Create pointsets of the nodes
    pp1 = Pointset(3)
    for node in graph1:
        pp1.append(node)    
    pp2 = Pointset(3)
    for node in graph2:
        pp2.append(node)    
    
    # Match the nodes of graph1 to graph2
    for node in graph1:
        dists = node.distance(pp2)
        i, = np.where(dists==dists.min())
        node.match = None
        if len(i):
            i = int(i[0])
            dist = float(dists[i])
            if dist < maxDist:
                node.match = graph2[i]
#         if not hasattr(node, 'dontCare'):
#             node.dontCare = False
    
    # Match the nodes of graph2 to graph1
    for node in graph2:
        dists = node.distance(pp1)
        i, = np.where(dists==dists.min())
        node.match = None
        if len(i):
            i = int(i[0])
            dist = float(dists[i])
            if dist < maxDist:
                node.match = graph1[i]
#         if not hasattr(node, 'dontCare'):
#             node.dontCare = False
    
    # Init amounts
    nmatch1, nmatch2, nmiss, nwrong = 0,0,0,0
    
    # Count matches and wrongs    
    for c in graph1.GetEdges():        
        end1 = c.end1.match
        end2 = c.end2.match
        if end1 and end2:
            if end1 in end2.GetNeighbours():
                nmatch1 += 1
                continue
#         elif c.end1.dontCare or c.end2.dontCare:
#             continue
        nwrong += 1
    
    # todo: use dontCare 'beleid' or not?
    
    # Count matches and misses
    for c in graph2.GetEdges():        
        end1 = c.end1.match
        end2 = c.end2.match
        if end1 and end2:
            if end1 in end2.GetNeighbours():
                nmatch2 += 1
                continue
#         elif c.end1.dontCare or c.end2.dontCare:
#             continue
        nmiss += 1
    
    # Compose score
    return MatchingScore(nmatch1, nmiss, nwrong)
Example #9
0
It also shows the different techniques to apply color to the meshes using
plain color, colormaps and texture.

On the website, this example also demonstrates the fly camera to fly through 
the mesh objects.

"""

import numpy as np
import visvis as vv
from visvis import Point, Pointset
vv.figure()
a = vv.gca()

# Define points for the line
pp = Pointset(3)
pp.append(0,0,0); pp.append(0,1,0); pp.append(1,2,0); pp.append(0,2,1)

# Create all solids
box = vv.solidBox((0,0,0))
sphere = vv.solidSphere((3,0,0))
cone = vv.solidCone((6,0,0))
pyramid = vv.solidCone((9,0,0), N=4) # a cone with 4 faces is a pyramid
cylinder = vv.solidCylinder((0,3,0),(1,1,2))
ring = vv.solidRing((3,3,0))
teapot = vv.solidTeapot((6,3,0))
line = vv.solidLine(pp+Point(9,3,0), radius = 0.2)

# Let's put a face on that cylinder
# This works because 2D texture coordinates are automatically generated for
# the sphere, cone, cylinder and ring. 
Example #10
0
class Drawer:
    def __init__(self):

        # Create figure and axes
        vv.figure()
        self._a = a = vv.gca()
        vv.title("Hold mouse to draw lines. Use 'rgbcmyk' and '1-9' keys.")

        # Set axes
        a.SetLimits((0, 1), (0, 1))
        a.cameraType = "2d"
        a.daspectAuto = False
        a.axis.showGrid = True

        # Init variables needed during drawing
        self._active = None
        self._pp = Pointset(2)

        # Create null and empty line objects
        self._line1 = None
        self._line2 = vv.plot(vv.Pointset(2), ls="+", lc="c", lw="2", axes=a)

        # Bind to events
        a.eventMouseDown.Bind(self.OnDown)
        a.eventMouseUp.Bind(self.OnUp)
        a.eventMotion.Bind(self.OnMotion)
        a.eventKeyDown.Bind(self.OnKey)

    def OnKey(self, event):
        """ Called when a key is pressed down in the axes.
        """

        if event.text and event.text.lower() in "rgbcmywk":
            self._line2.lc = event.text.lower()
        else:
            try:
                tickness = int(event.text)
            except Exception:
                tickness = 0
            if tickness > 0:
                self._line2.lw = tickness

    def OnDown(self, event):
        """ Called when the mouse is pressed down in the axes.
        """

        # Only process left mouse button
        if event.button != 1:
            return False

        # Store location
        self._active = Point(event.x2d, event.y2d)

        # Clear temp line object
        if self._line1:
            self._line1.Destroy()

        # Create line objects
        tmp = Pointset(2)
        tmp.append(self._active)
        tmp.append(self._active)
        self._line1 = vv.plot(tmp, lc="r", lw="1", axes=self._a, axesAdjust=0)

        # Draw
        self._a.Draw()

        # Prevent dragging by indicating the event needs no further handling
        return True

    def OnMotion(self, event):
        """ Called when the mouse is moved in the axes.
        """

        if self._active and self._line1:
            # Update line
            tmp = Pointset(2)
            tmp.append(self._active)
            tmp.append(event.x2d, event.y2d)
            self._line1.SetPoints(tmp)
            # Draw
            self._a.Draw()

    def OnUp(self, event):
        """ Called when the mouse is released (when first pressed down 
        in the axes).
        """

        # Only if a point is active
        if self._active is None:
            return False

        # Get points
        p1 = self._active
        p2 = Point(event.x2d, event.y2d)

        # Add!
        self._pp.append(p1)
        self._pp.append(p2)

        # We're done with this one
        self._active = None

        # Clear temp line object
        if self._line1:
            self._line1.Destroy()
            self._line1 = None

        # Update lines
        self._line2.SetPoints(self._pp)

        # Draw
        self._a.Draw()