예제 #1
0
def surface(volume, threshold=0.5, verbose=1):
    verts, faces = measure.marching_cubes(volume, threshold)

    if verbose == 2:
        import visvis as vv
        vv.mesh(np.fliplr(verts), faces)
        vv.use().Run()
예제 #2
0
def visualize(im, vol, sz=0.25, thr=0.99):
    im, vol = im.numpy(), vol.numpy()
    print("Image shape:", im.shape)
    print("Volume shape:", vol.shape)

    # overlap with 3d representation + BGR->RGB
    im = im.transpose(1, 2, 0)  # H,W,C
    im = im[:, :, ::-1]
    im = cv2.resize(im, (128, 128))

    t = vv.imshow(im)
    t.interpolate = True  # interpolate pixels

    # volshow will use volshow3 and rendering the isosurface if OpenGL version is >= 2.0
    # Otherwise, it will show slices with bars that you can move (much less useful).
    im = (im * 128 + 128).astype(np.uint8)
    # im = np.ones_like(im)

    volRGB = np.stack(((vol >= thr) * im[:, :, 0], (vol >= thr) * im[:, :, 1],
                       (vol >= thr) * im[:, :, 2]),
                      axis=3)

    v = vv.volshow(volRGB, renderStyle='iso')
    v.transformations[1].sz = sz  # Z rescaling

    l0 = vv.gca()
    l0.light0.ambient = 0.9  # 0.2 is default for light 0
    l0.light0.diffuse = 1.0  # 1.0 is default

    a = vv.gca()
    a.axis.visible = 0
    a.camera.fov = 0  # orthographic
    vv.use().Run()
예제 #3
0
def crop3d(vol, fig=None):
    """ crop3d(vol, fig=None)
    Manually crop a volume. In the given figure (or a new figure if None),
    three axes are created that display the transversal, sagittal and
    coronal MIPs (maximum intensity projection) of the volume. The user
    can then use the mouse to select a 3D range to crop the data to.
    """
    vv.use()

    # Create figure?
    if fig is None:
        fig = vv.figure()
        figCleanup = True
    else:
        fig.Clear()
        figCleanup = False

    # Create three axes and a wibject to attach text labels to
    a1 = vv.subplot(221)
    a2 = vv.subplot(222)
    a3 = vv.subplot(223)
    a4 = vv.Wibject(fig)
    a4.position = 0.5, 0.5, 0.5, 0.5

    # Set settings
    for a in [a1, a2, a3]:
        a.showAxis = False

    # Create cropper3D instance
    cropper3d = Cropper3D(vol, a1, a3, a2, a4)

    # Enter a mainloop
    while not cropper3d._finished:
        vv.processEvents()
        time.sleep(0.01)

    # Clean up figure (close if we opened it)
    fig.Clear()
    fig.DrawNow()
    if figCleanup:
        fig.Destroy()

    # Obtain ranges
    rx = cropper3d._range_transversal._rangex
    ry = cropper3d._range_transversal._rangey
    rz = cropper3d._range_coronal._rangey

    # Perform crop
    # make sure we have int not float
    rzmin, rzmax = int(rz.min), int(rz.max)
    rymin, rymax = int(ry.min), int(ry.max)
    rxmin, rxmax = int(rx.min), int(rx.max)
    vol2 = vol[rzmin:rzmax, rymin:rymax, rxmin:rxmax]
    # vol2 = vol[rz.min:rz.max, ry.min:ry.max, rx.min:rx.max]

    # Done
    return vol2
def main(select=3, **kwargs):
    """Script main function.

    select: int
        1: Medical data
        2: Blocky data, different every time
        3: Two donuts
        4: Ellipsoid

    """
    import visvis as vv  # noqa: delay import visvis and GUI libraries

    # Create test volume
    if select == 1:
        vol = vv.volread('stent')
        isovalue = kwargs.pop('level', 800)
    elif select == 2:
        vol = vv.aVolume(20, 128)
        isovalue = kwargs.pop('level', 0.2)
    elif select == 3:
        with timer('computing donuts'):
            vol = donuts()
        isovalue = kwargs.pop('level', 0.0)
        # Uncommenting the line below will yield different results for
        # classic MC
        # vol *= -1
    elif select == 4:
        vol = ellipsoid(4, 3, 2, levelset=True)
        isovalue = kwargs.pop('level', 0.0)
    else:
        raise ValueError('invalid selection')

    # Get surface meshes
    with timer('finding surface lewiner'):
        vertices1, faces1 = marching_cubes_lewiner(vol, isovalue, **kwargs)[:2]

    with timer('finding surface classic'):
        vertices2, faces2 = marching_cubes_classic(vol, isovalue, **kwargs)

    # Show
    vv.figure(1)
    vv.clf()
    a1 = vv.subplot(121)
    vv.title('Lewiner')
    m1 = vv.mesh(np.fliplr(vertices1), faces1)
    a2 = vv.subplot(122)
    vv.title('Classic')
    m2 = vv.mesh(np.fliplr(vertices2), faces2)
    a1.camera = a2.camera

    # visvis uses right-hand rule, gradient_direction param uses left-hand rule
    m1.cullFaces = m2.cullFaces = 'front'  # None, front or back

    vv.use().Run()
예제 #5
0
def main(select=3, **kwargs):
    """Script main function.

    select: int
        1: Medical data
        2: Blocky data, different every time
        3: Two donuts
        4: Ellipsoid

    """
    import visvis as vv  # noqa: delay import visvis and GUI libraries

    # Create test volume
    if select == 1:
        vol = vv.volread('stent')
        isovalue = kwargs.pop('level', 800)
    elif select == 2:
        vol = vv.aVolume(20, 128)
        isovalue = kwargs.pop('level', 0.2)
    elif select == 3:
        with timer('computing donuts'):
            vol = donuts()
        isovalue = kwargs.pop('level', 0.0)
        # Uncommenting the line below will yield different results for
        # classic MC
        # vol *= -1
    elif select == 4:
        vol = ellipsoid(4, 3, 2, levelset=True)
        isovalue = kwargs.pop('level', 0.0)
    else:
        raise ValueError('invalid selection')

    # Get surface meshes
    with timer('finding surface lewiner'):
        vertices1, faces1 = marching_cubes_lewiner(vol, isovalue, **kwargs)[:2]

    with timer('finding surface classic'):
        vertices2, faces2 = marching_cubes_classic(vol, isovalue, **kwargs)

    # Show
    vv.figure(1)
    vv.clf()
    a1 = vv.subplot(121)
    vv.title('Lewiner')
    m1 = vv.mesh(np.fliplr(vertices1), faces1)
    a2 = vv.subplot(122)
    vv.title('Classic')
    m2 = vv.mesh(np.fliplr(vertices2), faces2)
    a1.camera = a2.camera

    # visvis uses right-hand rule, gradient_direction param uses left-hand rule
    m1.cullFaces = m2.cullFaces = 'front'  # None, front or back

    vv.use().Run()
예제 #6
0
    def init_form(self):
        self._form = QWidget()
        layout = QVBoxLayout()
        layout.setMargin(0)

        if conf.PYFORMS_USE_QT5:
            layout.setContentsMargins(0, 0, 0, 0)
        else:
            layout.setMargin(0)

        self._form.setLayout(layout)
        self._app = vv.use('pyqt4')
        self._app.Create()
        self._first = True

        Figure = self._app.GetFigureClass()
        self._fig = Figure(self._form)
        vv.figure(self._fig.nr)

        policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        widget = self._fig._widget
        widget.setSizePolicy(policy)
        widget.setMinimumSize(100, 100)

        layout.addWidget(widget)

        self._colorMap = vv.CM_AUTUMN
        self._colors_limits = None
예제 #7
0
파일: show.py 프로젝트: simphony/nfluid
def show(items, normals=None):
    """Function that shows a mesh object.
    """
    for item in items:
        vv.clf()
        # convert to visvis.Mesh class
        new_normals = []
        new_vertices = []
        for k, v in item.vertices.iteritems():
            new_normals.append(item.normal(k))
            new_vertices.append(v)
        mesh = item.to_visvis_mesh()

        mesh.SetVertices(new_vertices)
        mesh.SetNormals(new_normals)
        mesh.faceColor = 'y'
        mesh.edgeShading = 'plain'
        mesh.edgeColor = (0, 0, 1)

    axes = vv.gca()
    if axes.daspectAuto is None:
        axes.daspectAuto = False
    axes.SetLimits()

    if normals is not None:
        for normal in normals:
            sl = solidLine(normal, 0.15)
            sl.faceColor = 'r'

    # Show title and enter main loop
    vv.title('Show')
    app = vv.use()
    app.Run()
예제 #8
0
    def init_form(self):
        self._form = QWidget()
        layout = QVBoxLayout()

        if _api.USED_API == _api.QT_API_PYQT5:
            layout.setContentsMargins(0, 0, 0, 0)
        elif _api.USED_API == _api.QT_API_PYQT4:
            layout.setMargin(0)

        self._form.setLayout(layout)
        self._app = vv.use('pyqt5')
        self._app.Create()
        self._first = True

        Figure = self._app.GetFigureClass()
        self._fig = Figure(self._form)
        vv.figure(self._fig.nr)

        policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        widget = self._fig._widget
        widget.setSizePolicy(policy)
        widget.setMinimumSize(100, 100)

        layout.addWidget(widget)

        self._colorMap = vv.CM_AUTUMN
        self._colors_limits = None
        super(ControlVisVisVolume, self).init_form()
예제 #9
0
def appInstance(useVisVis=True):
    """Create a suitable application instance"""
    print("Creating application instance...")

    global g_haveVisVis

    app = None

    if g_haveVisVis and useVisVis:
        print("Using VisVis application instance...")
        app = vv.use()
        app.Create()
    else:
        print("Trying Qt application instance...")
        app = QtGui.QApplication.instance()
        if app is None:
            print("Creating new Qt application instance...")
            app = QtGui.QApplication(sys.argv)
        else:
            print("Reusing existing Qt application instance...")

        if app != None:
            app.Run = app.exec_

    if app is None:
        print("No application instance found. Exiting...")
        sys.exit(-1)

    return app
예제 #10
0
 def __init__(self, audiofile=None, fs=22050, bandwidth=300,freqRange= 5000, dynamicRange=48, noiseFloor =-72, parent = None):
     super(Spec, self).__init__()
     
     backend = 'pyqt4'
     app = vv.use(backend)
     Figure = app.GetFigureClass()
     self.fig= Figure(self)
     self.fig.enableUserInteraction = True
     self.fig._widget.setMinimumSize(700,350)
     self.axes = vv.gca()
     
     self.audiofilename = audiofile
     self.freqRange = freqRange
     self.fs = fs
     self.NFFT = int(1.2982804/bandwidth*self.fs)
     self.overlap = int(self.NFFT/2)
     self.noiseFloor = noiseFloor
     self.dynamicRange = dynamicRange
     self.timeLength = 60
     self.resize(700,250)
     
     layout = QtGui.QVBoxLayout()
     layout.addWidget(self.fig._widget)
     self.setLayout(layout)
     
     self.win = gaussian(self.NFFT,self.NFFT/6)
     self.show()
예제 #11
0
파일: ui.py 프로젝트: CALFEM/calfem-python
def appInstance(useVisVis=True):
    """Create a suitable application instance"""
    print("Creating application instance...")
    
    global g_haveVisVis
    
    app = None
    
    if g_haveVisVis and useVisVis:
        print("Using VisVis application instance...")
        app = vv.use()
        app.Create()
    else:
        print("Trying Qt application instance...") 
        app = QtGui.QApplication.instance()
        if app is None:
            print("Creating new Qt application instance...")
            app = QtGui.QApplication(sys.argv)
        else:
            print("Reusing existing Qt application instance...")
        
        if app!=None:
            app.Run = app.exec_
            
    if app is None:
        print("No application instance found. Exiting...")
        sys.exit(-1)

    return app    
예제 #12
0
def _visualise_world_visvis(X, Y, Z, format="surf"):
    """
    Legacy function to produce a surface render using visvis
    :param X:
    :param Y:
    :param Z:
    :param format:
    """
    import visvis as vv

    # m2 = vv.surf(worldx[::detail], worldy[::detail], worldz[::detail])

    app = vv.use()
    # prepare axes
    a = vv.gca()
    a.cameraType = '3d'
    a.daspectAuto = False
    # print("view", a.camera.GetViewParams())
    # a.SetView(loc=(-1000,0,0))
    # a.camera.SetView(None, loc=(-1000,0,0))

    if format == "surf":
        l = vv.surf(X, Y, Z)
        a.SetLimits(rangeX=(-0.2, 0.2),
                    rangeY=(-0.5, 0.5),
                    rangeZ=(-0.5, 0),
                    margin=0.02)
    else:
        # draw points
        pp = vv.Pointset(
            np.concatenate([X.flatten(), Y.flatten(),
                            Z.flatten()], axis=0).reshape((-1, 3)))
        l = vv.plot(pp, ms='.', mc='r', mw='5', ls='', mew=0)
        l.alpha = 0.2
    app.Run()
예제 #13
0
파일: vis.py 프로젝트: jupito/dwilib
def main():
    p = Path('/mri/images/DWI-Mono/42-1a/42-1a_ADCm.zip')
    image = Image.read(p, dtype='float32')
    image = image[image.mbb()]

    app = vv.use()
    # vv.figure()
    # vv.title(p.name)
    plot(image)
    app.Run()
예제 #14
0
파일: vis.py 프로젝트: parisa1365/dwilib
def main():
    p = Path('/mri/images/DWI-Mono/42-1a/42-1a_ADCm.zip')
    image = Image.read(p, dtype='float32')
    image = image[image.mbb()]

    app = vv.use()
    # vv.figure()
    # vv.title(p.name)
    plot(image)
    app.Run()
예제 #15
0
def plot_3d(image, threshold=100):
    # Position the scan upright,
    # so the head of the patient would be at the top facing the camera
    p = image.transpose(2, 1, 0)
    p = p[::2, ::2, ::2]
    #     verts, faces = measure.marching_cubes(p, threshold)
    # verts, faces,_,_ = measure.marching_cubes_lewiner(p, threshold)

    verts, faces, normals, values = measure.marching_cubes(p, threshold)
    '''
    verts, faces, normals, values = marching_cubes_lewiner(myvolume, 0.0) # doctest: +SKIP
      >>> vv.mesh(np.fliplr(verts), faces, normals, values) # doctest: +SKIP
      >>> vv.use().Run() # doctest: +SKIP
      
    '''

    lung_mesh = vv.mesh(np.fliplr(verts),
                        faces,
                        normals,
                        values,
                        verticesPerFace=4,
                        colormap=None,
                        clim=None,
                        texture=None,
                        axesAdjust=True,
                        axes=None)
    #     lung_mesh.setcolor([0.45, 0.45, 0.75])
    faceColor = 'g'
    vv.use().Run()

    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection='3d')
    # Fancy indexing: `verts[faces]` to generate a collection of triangles
    mesh = Poly3DCollection(verts[faces], alpha=0.1)
    face_color = [0.5, 0.5, 1]
    mesh.set_facecolor(face_color)
    ax.add_collection3d(mesh)
    ax.set_xlim(0, p.shape[0])
    ax.set_ylim(0, p.shape[1])
    ax.set_zlim(0, p.shape[2])
    plt.show()
    def initControl(self):        
        self._form = QtGui.QWidget();layout = QtGui.QVBoxLayout();layout.setMargin(0);self._form.setLayout( layout )
        self._app = vv.use('pyqt4')

        Figure = self._app.GetFigureClass()
        self._fig = Figure(self._form)

        policy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        widget = self._fig._widget
        widget.setSizePolicy(policy)

        layout.addWidget(widget)
예제 #17
0
def crop3d(vol, fig=None):
    """ crop3d(vol, fig=None)
    Manually crop a volume. In the given figure (or a new figure if None),
    three axes are created that display the transversal, sagittal and 
    coronal MIPs (maximum intensity projection) of the volume. The user
    can then use the mouse to select a 3D range to crop the data to.
    """
    app = vv.use()
    
    # Create figure?    
    if fig is None:        
        fig = vv.figure()    
        figCleanup = True
    else:
        fig.Clear()
        figCleanup = False
    
    # Create three axes and a wibject to attach text labels to    
    a1 = vv.subplot(221)
    a2 = vv.subplot(222)
    a3 = vv.subplot(223)
    a4 = vv.Wibject(fig)
    a4.position = 0.5, 0.5, 0.5, 0.5
    
    # Set settings
    for a in [a1, a2, a3]:
        a.showAxis = False
    
    # Create cropper3D instance
    cropper3d = Cropper3D(vol, a1, a3, a2, a4)
    
    # Enter a mainloop
    while not cropper3d._finished:
        vv.processEvents()
        time.sleep(0.01)
    
    # Clean up figure (close if we opened it)
    fig.Clear()
    fig.DrawNow()
    if figCleanup:    
        fig.Destroy()
    
    # Obtain ranges
    rx = cropper3d._range_transversal._rangex
    ry = cropper3d._range_transversal._rangey
    rz = cropper3d._range_coronal._rangey
    
    # Perform crop
    vol2 = vol[rz.min:rz.max, ry.min:ry.max, rx.min:rx.max]
    
    # Done
    return vol2
예제 #18
0
파일: dev_utils.py 프로젝트: twguest/WPG
def visVol(volData):
    """ This example demonstrates rendering a color volume.
    We demonstrate two renderers capable of rendering color data:
    the colormip and coloriso renderer.
    """

    import visvis as vv

    app = vv.use()

    # Load volume
    vol = volData

    # set labels
    vv.xlabel("x axis")
    vv.ylabel("y axis")
    vv.zlabel("z axis")

    #    # Create figure and make subplots with different renderers
    #    vv.figure(1); vv.clf()
    #    RS = ['mip', 'iso', 'edgeray', 'ray', 'litray']
    #    a0 = None
    #    tt = []
    #    for i in range(5):
    #        a = vv.subplot(3,2,i+2)
    #        t = vv.volshow(vol)
    #        vv.title('Renderstyle ' + RS[i])
    #        t.colormap = vv.CM_HOT
    #        t.renderStyle = RS[i]
    #        t.isoThreshold = 200  # Only used in iso render style
    #        tt.append(t)
    #        if a0 is None:
    #            a0 = a
    #        else:
    #            a.camera = a0.camera
    t = vv.volshow(vol, renderStyle="edgeray")
    t.colormap = vv.CM_HOT

    # Get axes and set camera to orthographic mode (with a field of view of 70)
    a = vv.gca()
    a.camera.fov = 45

    # Create colormap editor wibject.
    vv.ColormapEditor(a)

    # Create colormap editor in first axes
    # cme = vv.ColormapEditor(vv.gcf(), t)

    # Run app
    # app.Create()
    app.Run()
예제 #19
0
    def initForm(self):
        self._form = QtGui.QWidget()
        layout = QtGui.QVBoxLayout()
        layout.setMargin(0)
        self._form.setLayout(layout)
        self._app = vv.use('pyqt4')
        self._app.Create()

        Figure = self._app.GetFigureClass()
        self._fig = Figure(self._form)

        policy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        widget = self._fig._widget
        widget.setSizePolicy(policy)

        layout.addWidget(widget)
예제 #20
0
    def initForm(self):
        self._form = QtGui.QWidget();layout = QtGui.QVBoxLayout();layout.setMargin(0);self._form.setLayout( layout )
        self._app = vv.use('pyqt4')
        self._first=True

        Figure = self._app.GetFigureClass()
        self._fig = Figure(self._form)
        vv.figure(self._fig.nr)
        
        policy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        widget = self._fig._widget
        widget.setSizePolicy(policy)
        widget.setMinimumSize(100, 100)

        layout.addWidget(widget)

        self._colorMap = vv.CM_AUTUMN
예제 #21
0
    def __init__(self, sampleinterval=0.1, timewindow=10.0, size=(600, 350)):
        # Data stuff
        self._interval = int(sampleinterval * 1000)
        self._bufsize = int(timewindow / sampleinterval)
        self.databuffer = collections.deque([0.0] * self._bufsize, self._bufsize)
        self.x = np.linspace(-timewindow, 0.0, self._bufsize)
        self.y = np.zeros(self._bufsize, dtype=np.float)
        # Visvis stuff
        self.app = vv.use("qt4")
        vv.title("Dynamic Plotting with VisVis")
        self.line = vv.plot(self.x, self.y, lc="b", lw=3, ms="+")
        vv.xlabel("time")
        vv.ylabel("amplitude")
        self.ax = vv.gca()

        self.timer = vv.Timer(self.app, 50, oneshot=False)
        self.timer.Bind(self.updateplot)
        self.timer.Start()
예제 #22
0
    def show(self):
        for projection_name in self.rsa_assessment.projection_list():
            rsa_projection = self.rsa_assessment.projection(projection_name)

            # projection = self.assessment.projection(i)
            # projector = self.projectors[i]
            self.plot_image_data(rsa_projection.image,
                                 rsa_projection.t,
                                 sampling=0.1)

            for image_segment_name in rsa_projection.image_segment_list():
                try:
                    rsa_image_segment = rsa_projection.image_segment(
                        image_segment_name)
                except NotImplementedError:
                    continue

                for line in rsa_projection.segment_point_lines(
                        rsa_image_segment):
                    ps = vv.Pointset(3)
                    ps.append(*list(line.a[:3]))
                    ps.append(*list(line.b[:3]))
                    vl = vv.solidLine(ps, radius=self.lineSize, N=self.lineN)
                    vl.faceColor = self.lineColor

        for scene_segment_name in self.rsa_assessment.scene_segment_list():
            try:
                scene_segment = self.rsa_assessment.scene_segment(
                    scene_segment_name)
            except NotImplementedError:
                continue

            scene_segment.match_crossing_lines()
            for i in range(len(scene_segment.points)):
                vs = vv.solidSphere(translation=tuple(
                    scene_segment.points[i][:3]),
                                    scaling=([self.pointSize] * 3),
                                    N=self.sphereN,
                                    M=self.sphereM)
                vs.faceColor = self.pointColor

        # Enter main loop
        app = vv.use()
        app.Run()
예제 #23
0
    def __init__(self, sampleinterval=0.1, timewindow=10., size=(600, 350)):
        # Data stuff
        self._interval = int(sampleinterval * 1000)
        self._bufsize = int(timewindow / sampleinterval)
        self.databuffer = collections.deque([0.0] * self._bufsize,
                                            self._bufsize)
        self.x = np.linspace(-timewindow, 0.0, self._bufsize)
        self.y = np.zeros(self._bufsize, dtype=np.float)
        # Visvis stuff
        self.app = vv.use('qt4')
        vv.title('Dynamic Plotting with VisVis')
        self.line = vv.plot(self.x, self.y, lc='b', lw=3, ms='+')
        vv.xlabel('time')
        vv.ylabel('amplitude')
        self.ax = vv.gca()

        self.timer = vv.Timer(self.app, 50, oneshot=False)
        self.timer.Bind(self.updateplot)
        self.timer.Start()
예제 #24
0
    def show_vox(self, vfunc):
        """
        Displays a 3-D rendering of a voxelized property.
        :param vfunc: function accepting this MasonView instance and
            returning a 3-D np.array of some voxelized property
        """
        app = vv.use()
        vv.figure(1)
        vv.xlabel('Eastings (units)')
        vv.ylabel('Northings (units)')
        vv.zlabel('Depth (units)')
        a = vv.gca()
        a.camera.fov = 70
        a.daspect = 1, 1, -1
        vox = vfunc(self)
        t = vv.volshow(vox, cm=vv.CM_JET, renderStyle='ray')

        vv.ColormapEditor(a)
        app.Run()
예제 #25
0
def psf_volume(stack, xyz_ratio, filepath):

    app = vv.use()
    # Init a figure with two axes
    a1 = vv.subplot(121)
    vv.title('PSF Volume')
    a2 = vv.subplot(122)
    vv.title('PSF XYZ Cross Sections')
    
    # show
    t1 = vv.volshow(stack, axes=a1)  # volume
    t2 = vv.volshow2(stack, axes=a2)  # cross-section interactive
       
    # set labels for both axes
    vv.xlabel('Pixel X', axes=a1)
    vv.ylabel('Pixel Y', axes=a1)
    vv.zlabel('Z-Slice', axes=a1)
    vv.xlabel('Pixel X', axes=a2)
    vv.ylabel('Pixel Y', axes=a2)
    vv.zlabel('Z-Slice', axes=a2)
    
    # set colormaps
    t1.colormap = vv.CM_JET
    t2.colormap = vv.CM_JET

    # set correct aspect ration corresponding to voxel size    
    a1.daspect = 1, 1, xyz_ratio
    a2.daspect = 1, 1, xyz_ratio
    
    # show grid
    a1.axis.showGrid = 1
    a2.axis.showGrid = 1    
    
    # run visvis and show results
    app.Run()

    # save screenshot
    if filepath != 'nosave':
        print 'Saving PSF volume.'
        savename = filepath[:-4] + '_PSF_3D.png'
        # sf: scale factor
        vv.screenshot(savename, sf=1, bg='w')
예제 #26
0
	def init_form(self):        
		self._form = QWidget()
		layout = QVBoxLayout()
		
		if conf.PYFORMS_USE_QT5:
			layout.setContentsMargins(0,0,0,0)
		else:
			layout.setMargin(0)

		self._form.setLayout( layout )
		self._app = vv.use('pyqt5')
		self._app.Create()
		
		Figure = self._app.GetFigureClass()
		self._fig = Figure(self._form)

		policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
		widget = self._fig._widget
		widget.setSizePolicy(policy)

		layout.addWidget(widget)
예제 #27
0
    def init_form(self):
        self._form = QWidget()
        layout = QVBoxLayout()

        if _api.USED_API == _api.QT_API_PYQT5:
            layout.setContentsMargins(0, 0, 0, 0)
        else:
            layout.setMargin(0)

        self._form.setLayout(layout)
        self._app = vv.use('pyqt5')
        self._app.Create()

        Figure = self._app.GetFigureClass()
        self._fig = Figure(self._form)

        policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        widget = self._fig._widget
        widget.setSizePolicy(policy)

        layout.addWidget(widget)
        super(ControlVisVis, self).init_form()
예제 #28
0
    def initForm(self):
        self._form = QtGui.QWidget()
        layout = QtGui.QVBoxLayout()
        layout.setMargin(0)
        self._form.setLayout(layout)
        self._app = vv.use('pyqt4')
        self._app.Create()
        self._first = True

        Figure = self._app.GetFigureClass()
        self._fig = Figure(self._form)
        vv.figure(self._fig.nr)

        policy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding,
                                   QtGui.QSizePolicy.Expanding)
        widget = self._fig._widget
        widget.setSizePolicy(policy)
        widget.setMinimumSize(100, 100)

        layout.addWidget(widget)

        self._colorMap = vv.CM_AUTUMN
예제 #29
0
    def show_layer_boundaries(self, sample):
        """
        Displays a 3-D rendering of boundary surfaces.
        :param sample: index of sample for which to plot boundaries
        """
        app = vv.use()
        vv.figure(1)
        X = np.linspace(self.xbounds[0], self.xbounds[1], self.xres)
        Y = np.linspace(self.ybounds[0], self.xbounds[1], self.yres)
        Z = np.linspace(self.zbounds[0], self.xbounds[1], self.zres)
        vv.xlabel('Eastings (m)')
        vv.ylabel('Northings (m)')
        vv.zlabel('Depth (m)')
        a = vv.gca()
        a.camera.fov = 70
        a.daspect = 1, 1, -1
        for i in range(len(self.layers)):
            C = plt.cm.jet(i / float(len(self.layers)))
            C = np.array([[[C[0], C[1], C[2]]]])
            m = vv.surf(X, Y, self.fbounds[i][sample], C)

        vv.ColormapEditor(a)
        app.Run()
예제 #30
0
# Display a legend
a1.legend = "Lena's face", "Lena's shoulder"


# Create second axes (with a black background)
a2 = vv.subplot(122)
a2.bgcolor = 'k'
a2.axis.axisColor = 'w'

# Display a texture 
vol = vv.aVolume(2) # returns a test volume as a numpy array
texture3d = vv.volshow(vol)

# Display a mesh using one of the "solid" functions
mesh = vv.solidTeapot((32,32,80), scaling=(50,50,50))
mesh.faceColor = 0.4, 1, 0.4
mesh.specular = 'r'

# Set orthographic projection
a2.camera.fov = 45

# Create labels for the axis
a2.axis.xLabel = 'x-axis'
a2.axis.yLabel = 'y-axis'
a2.axis.zLabel = 'z-axis'

# Enter main loop
app = vv.use() # let visvis chose a backend for me
app.Run()
예제 #31
0
def demo(*args, **kwargs):
    import math
    m = 80  # width of grid
    n = m ** 2  # number of points

    minVal = -2.0
    maxVal = 2.0
    delta = (maxVal - minVal) / (m - 1)
    X, Y = numpy.mgrid[minVal:maxVal + delta:delta, minVal:maxVal + delta:delta]

    X = X.flatten()
    Y = Y.flatten()

    Z = numpy.sin(X) * numpy.cos(Y)

    # Create the data point-matrix
    M = numpy.array([X, Y, Z]).T

    # Translation values (a.u.):
    Tx = 0.5
    Ty = -0.3
    Tz = 0.2

    # Translation vector
    T = numpyTransform.translation(Tx, Ty, Tz)

    S = numpyTransform.scaling(1.0, N=4)

    # Rotation values (rad.):
    rx = 0.3
    ry = -0.2
    rz = 0.05

    Rx = numpy.matrix([[1, 0, 0, 0],
                      [0, math.cos(rx), -math.sin(rx), 0],
                      [0, math.sin(rx), math.cos(rx), 0],
                      [0, 0, 0, 1]])

    Ry = numpy.matrix([[math.cos(ry), 0, math.sin(ry), 0],
                       [0, 1, 0, 0],
                       [-math.sin(ry), 0, math.cos(ry), 0],
                       [0, 0, 0, 1]])

    Rz = numpy.matrix([[math.cos(rz), -math.sin(rz), 0, 0],
                       [math.sin(rz), math.cos(rz), 0, 0],
                       [0, 0, 1, 0],
                       [0, 0, 0, 1]])

    # Rotation matrix
    R = Rx * Ry * Rz

    transformMat = numpy.matrix(numpy.identity(4))
    transformMat *= T
    transformMat *= R
    transformMat *= S

    # Transform data-matrix plus noise into model-matrix
    D = numpyTransform.transformPoints(transformMat, M)

    # Add noise to model and data
    M = M + 0.01 * numpy.random.randn(n, 3)
    D = D + 0.01 * numpy.random.randn(n, 3)

    # Run ICP (standard settings)
    initialGuess = numpy.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
    lowerBounds = numpy.array([-pi, -pi, -pi, -100.0, -100.0, -100.0])
    upperBounds = numpy.array([pi, pi, pi, 100.0, 100.0, 100.0])
    icp = ICP(M, D, maxIterations=15, dataDownsampleFactor=1, minimizeMethod='fmincon', **kwargs)
#    icp = ICP(M, D, maxIterations=15, dataDownsampleFactor=1, minimizeMethod='point', **kwargs)
    transform, err, t = icp.runICP(x0=initialGuess, lb=lowerBounds, ub=upperBounds)

    # Transform data-matrix using ICP result
    Dicp = numpyTransform.transformPoints(transform[-1], D)

    # Plot model points blue and transformed points red
    if False:
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D
        fig = plt.figure()
        ax = fig.add_subplot(2, 2, 1, projection='3d')
        ax.scatter(M[:, 0], M[:, 1], M[:, 2], c='r', marker='o')
        ax.scatter(D[:, 0], D[:, 1], D[:, 2], c='b', marker='^')
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z Label')

        ax = fig.add_subplot(2, 2, 2, projection='3d')
        ax.scatter(M[:, 0], M[:, 1], M[:, 2], c='r', marker='o')
        ax.scatter(Dicp[:, 0], Dicp[:, 1], Dicp[:, 2], c='b', marker='^')
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')
        ax.set_zlabel('Z Label')

        ax = fig.add_subplot(2, 2, 3)
        ax.plot(t, err, 'x--')
        ax.set_xlabel('X Label')
        ax.set_ylabel('Y Label')

        plt.show()
    else:
        import visvis as vv
        app = vv.use()
        vv.figure()
        vv.subplot(2, 2, 1)
        vv.plot(M[:, 0], M[:, 1], M[:, 2], lc='b', ls='', ms='o')
        vv.plot(D[:, 0], D[:, 1], D[:, 2], lc='r', ls='', ms='x')
        vv.xlabel('[0,0,1] axis')
        vv.ylabel('[0,1,0] axis')
        vv.zlabel('[1,0,0] axis')
        vv.title('Red: z=sin(x)*cos(y), blue: transformed point cloud')

        # Plot the results
        vv.subplot(2, 2, 2)
        vv.plot(M[:, 0], M[:, 1], M[:, 2], lc='b', ls='', ms='o')
        vv.plot(Dicp[:, 0], Dicp[:, 1], Dicp[:, 2], lc='r', ls='', ms='x')
        vv.xlabel('[0,0,1] axis')
        vv.ylabel('[0,1,0] axis')
        vv.zlabel('[1,0,0] axis')
        vv.title('ICP result')

        # Plot RMS curve
        vv.subplot(2, 2, 3)
        vv.plot(t, err, ls='--', ms='x')
        vv.xlabel('time [s]')
        vv.ylabel('d_{RMS}')
        vv.title('KD-Tree matching')
        if 'optAlg' in kwargs:
            opt2 = nlopt.opt(kwargs['optAlg'], 2)
            vv.title(opt2.get_algorithm_name())
            del opt2
        else:
            vv.title('KD-Tree matching')
        app.Run()
예제 #32
0
                    ) * ( ( (8*x)**2 + ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2 + 16 - 1.85*1.85 )
                    * ( (8*x)**2 + ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2 + 16 - 1.85*1.85 ) -
                    64 * ( ((8*y-2)+4)*((8*y-2)+4) + (8*z)**2
                    ) ) + 1025
    # Uncommenting the line below will yield different results for classic MC
    #vol = -vol

elif SELECT == 4:
    vol = ellipsoid(4, 3, 2, levelset=True)
    isovalue = 0

# Get surface meshes
t0 = time.time()
vertices1, faces1, _ = marching_cubes_lewiner(vol, isovalue, gradient_direction=gradient_dir, use_classic=False)
print('finding surface lewiner took %1.0f ms' % (1000*(time.time()-t0)) )

t0 = time.time()
vertices2, faces2, _ = marching_cubes_classic(vol, isovalue, gradient_direction=gradient_dir)
print('finding surface classic took %1.0f ms' % (1000*(time.time()-t0)) )

# Show
vv.figure(1); vv.clf()
a1 = vv.subplot(121); m1 = vv.mesh(np.fliplr(vertices1), faces1)
a2 = vv.subplot(122); m2 = vv.mesh(np.fliplr(vertices2), faces2)
a1.camera = a2.camera

# visvis uses right-hand rule, gradient_direction param uses left-hand rule
m1.cullFaces = m2.cullFaces = 'front'  # None, front or back

vv.use().Run()
예제 #33
0
#!/usr/bin/env python
""" 
This example illustrates embedding a visvis figure in a wx application.
"""

import wx
import visvis as vv

# Create a visvis app instance, which wraps a wx application object.
# This needs to be done *before* instantiating the main window. 
app = vv.use('wx')


class MainWindow(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Embedding in WX", size=(560, 420))
        
        # Make a panel with a button
        self.panel = wx.Panel(self)
        but = wx.Button(self.panel, -1, 'Click me')
        
        # Make figure using "self" as a parent
        Figure = app.GetFigureClass()
        self.fig = Figure(self)
        
        # Make sizer and embed stuff
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer.Add(self.panel, 1, wx.EXPAND)
        self.sizer.Add(self.fig._widget, 2, wx.EXPAND)
        
        # Make callback
예제 #34
0
#!/usr/bin/env python

import visvis as vv
app = vv.use()

# Get green channel of lena image
im = vv.imread('lena.png')[:,:,1]

# Make 4 subplots with different colormaps
cmaps = [vv.CM_GRAY, vv.CM_JET, vv.CM_SUMMER, vv.CM_HOT]
for i in range(4):
    a = vv.subplot(2,2,i+1)
    t = vv.imshow(im, clim=(0,255))
    a.axis.visible = 0
    t.colormap = cmaps[i]
    vv.colorbar()

app.Run()
예제 #35
0
 def __init__(self, display2d=True, camera_zoom=None, camera_location=None):
     self.app = vv.use('qt5')
     self.figsize = (1280 + 20, 720 + 20)
     self.display2d = display2d
     self.camera_zoom = camera_zoom
     self.camera_location = camera_location
예제 #36
0
#!/usr/bin/env python
""" 
This example illustrates embedding a visvis figure in an FLTK application.
"""

import fltk
import visvis as vv

# Create a visvis app instance, which wraps an fltk application object.
# This needs to be done *before* instantiating the main window.
app = vv.use("fltk")


class MainWindow(fltk.Fl_Window):
    def __init__(self):
        fltk.Fl_Window.__init__(self, 560, 420, "Embedding in FLTK")

        # Make a panel with a button
        but = fltk.Fl_Button(10, 10, 70, 30, "Click me")
        but.callback(self._Plot)

        # Make figure to draw stuff in
        Figure = app.GetFigureClass()
        self.fig = Figure(100, 10, 560 - 110, 420 - 20, "")

        # Make box for resizing
        box = fltk.Fl_Box(fltk.FL_NO_BOX, 100, 50, 560 - 110, 420 - 60, "")
        self.resizable(box)
        box.hide()

        # Finish
예제 #37
0
#!/usr/bin/env python
""" 
This example illustrates embedding a visvis figure in an FLTK application.
"""

import fltk
import visvis as vv

# Create a visvis app instance, which wraps an fltk application object.
# This needs to be done *before* instantiating the main window. 
app = vv.use('fltk')


class MainWindow(fltk.Fl_Window):
    def __init__(self):
        fltk.Fl_Window.__init__(self, 560, 420, "Embedding in FLTK")
        
        # Make a panel with a button
        but = fltk.Fl_Button(10,10,70,30, 'Click me')
        but.callback(self._Plot)
        
        # Make figure to draw stuff in
        self.fig = vv.backends.backend_fltk.Figure(100,10,560-110,420-20, "")
        
        # Make box for resizing
        box = fltk.Fl_Box(fltk.FL_NO_BOX,100,50, 560-110,420-60,"")
        self.resizable(box)
        box.hide()
        
        # Finish
        self.end()
예제 #38
0
#

import sys

import wx

from events import post_event, EventThread, Event


vvPresent = False
if not hasattr(sys, "frozen"):
    try:
        import visvis as vv
        from visvis.core.line import Line

        app = vv.use("wx")
        vvPresent = True
    except ImportError:
        pass


class PlotterPreview(object):
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.axes = None
        self.window = None
        self.preview = None

        self.__setup_plot()
예제 #39
0
import numpy as np
import matplotlib.pyplot as plt

import OpenGL.GL as gl  #@UnresolvedImport

from numpy import sin, cos, pi
from math import atan2

import logging as cflog

globalWindows = []  # For supporting ElementView:s for eldraw ...

global globalVisVisApp

global visApp
visApp = vv.use('qt5')  # use qt4


def error(msg):
    """Log error message"""
    cflog.error(msg)


def info(msg):
    """Log information message"""
    cflog.info(msg)


def figure_class():
    """Return visvis Figure class."""
    global visApp
예제 #40
0
파일: use.py 프로젝트: chiluf/visvis
    vv.settings.preferredBackend first.
    
    Note: the backend can be changed even when figures are created with
    another backend, but this is not recommended.
    
    Example embedding in Qt4
    ------------------------
    # Near the end of the script:
    
    # Get app instance and create native app
    app = vv.use('pyside')
    app.Create() 
    
    # Create window
    m = MainWindow()
    m.resize(560, 420)
    m.show()
    
    # Run main loop
    app.Run()
    
    """
    return vv.backends.use(backendName)


if __name__ == '__main__':
    app = vv.use()  # No arg provided: select backend automatically
    print('Selected backend is %s.' % app.GetBackendName())
    app.Create()  # Create the backend's application
    app.Run()  # Enter the backend's mainloop (not in interactive mode)
예제 #41
0
def view(mol, viewer='native'):
    '''Render the molecule

    The mayavi backend doesn't work under python 3. The native backend uses
    visvis to render the molecule. This is very slow.
    It's better to use the molecular viewer.

    Args:
        mol (molecule.Molecule): The molecule instance to render
        viewer: The backend to use. Valid choices are 'native', 'maya'
        and, 'avogadro' (default: native).

    Rturns:
        None
    '''
    # mayavi
    if viewer == 'maya':
        from mayavi import mlab
        for atom in mol.atoms:
            pts = mlab.points3d(atom.r[0], atom.r[1], atom.r[2],
                                scale_factor=0.75,
                                scale_mode='none',
                                resolution=20,
                                color=atom.color())
        for i, j in mol.bonds():
            mlab.plot3d([mol.atoms[i].r[0], mol.atoms[j].r[0]],
                        [mol.atoms[i].r[1], mol.atoms[j].r[1]],
                        [mol.atoms[i].r[2], mol.atoms[j].r[2]],
                        tube_radius=0.1,
                        tube_sides=20)
        mlab.show()

    # avogadro
    if viewer == 'avogadro':
        from subprocess import call
        write_xyz(mol, 'avogadro.xyz')
        call(['avogadro', 'avogadro.xyz'])
        call(['rm', 'avogadro.xyz'])

    # visvis
    if viewer == 'native':
        import visvis as vv

        for atom in mol.atoms:
            x, y, z = atom.r
            at = vv.solidSphere((x, y, z), atom.radius()*0.25)
            at.faceColor = atom.color()

        for bond in mol.bonds():
            pp = vv.Pointset(3)
            pp.append(bond.atoms[0].r)
            pp.append(bond.atoms[1].r)
            vv.solidLine(pp, radius=0.15, N=16)

        pp = vv.Pointset(3)
        pp.append([3, 3, 3])
        pp.append([4, 3, 3])
        x = vv.solidLine(pp, radius=0.05)
        x.faceColor = 'r'
        conex = vv.solidCone([4, 3, 3], scaling=[0.1, 0.1, 0.1], direction=[1, 0, 0])
        conex.faceColor = 'r'

        pp = vv.Pointset(3)
        pp.append([3, 3, 3])
        pp.append([3, 4, 3])
        y = vv.solidLine(pp, radius=0.05)
        y.faceColor = 'g'
        coney = vv.solidCone([3, 4, 3], scaling=[0.1, 0.1, 0.1], direction=[0, 1, 0])
        coney.faceColor = 'g'

        pp = vv.Pointset(3)
        pp.append([3, 3, 3])
        pp.append([3, 3, 4])
        z = vv.solidLine(pp, radius=0.05)
        z.faceColor = 'b'
        conez = vv.solidCone([3, 3, 4], scaling=[0.1, 0.1, 0.1], direction=[0, 0, 1])
        conez.faceColor = 'b'

        # Set axes settings
        axes = vv.gca()
        axes.SetLimits(rangeX=(-5, 5), rangeY=(-5, 5), rangeZ=(-5, 5))
        vv.axis('off')
        app = vv.use()
        app.Run()
예제 #42
0
    def plot(self, engine='pyplot', iterations=None):
        """Plots the system using a specified render engine.
        Needs compute_3d_vectrices() to be called before.
        - engine: String for the render engine. Can be 'pyplot', 'plotly' or 'visvis'.
        pyplot is the nicest because it supports antialiasing on translucent objects.
        plotly is a way faster alternative that uses your web browser's render engine.
        visvis is faster but a bit rough.
        - iterations: Limits the plotting to this number of iterations.
        If None, the whole system states will be plotted."""
        engine = engine.lower()
        if iterations is None:
            iterations = self.iterations
        elif iterations > self.iterations:
            raise ValueError("Unable to plot %s out of %s iterations"
                % (iterations, self.iterations))

        if engine == 'visvis':
            try:
                import visvis as vv
            except ImportError:
                raise ImportError("visvis must be installed in order to use it."
                "Try to 'pip install visvis' in a command line.")
            app = vv.use()
            fig = vv.clf()
            ax  = vv.cla()

        elif engine == 'pyplot':
            try:
                import matplotlib.pyplot as plt
                from mpl_toolkits.mplot3d import Axes3D
            except ImportError:
                raise ImportError("pyplot must be installed in order to use it."
                "Try to 'pip install matplotlib' in a command line.")
            fig = plt.figure(figsize=(32, 18), dpi=100)
            ax = fig.gca(projection='3d')
            ax.set_axis_off()

        elif engine == 'plotly':
            try:
                import plotly as pl
                from plotly.graph_objs import Scatter3d, Layout, Scene, Figure
            except ImportError:
                raise ImportError("plotly must be installed in order to use it."
                "Try to 'pip install plotly' in a command line.")
            data = []
            layout = Layout(
                scene = Scene(
                    xaxis=dict(
                        visible = False,
                        autorange = True,
                    ),
                    yaxis=dict(
                        visible = False,
                        autorange = True,
                    ),
                    zaxis=dict(
                        visible = False,
                        autorange = True,
                    )
                ),
                margin=dict(
                    r=0, l=0,
                    b=0, t=0
                ),
                showlegend = False,
                hovermode = False
            )

        else:
            raise ValueError("%s is not a supported render engine." % engine)


        rings  = self.rings[:iterations]
        for i, ring in enumerate(rings):
            color = self.cmap(i, 0, len(self.rings) / 2, 1)
            if engine == 'visvis':
                vv.plot(*ring, lc=color, mw=0, alpha=.2)
            elif engine == 'pyplot':
                ax.plot(*ring, c=color+(.4,)) # Adding alpha as (r, g, b, a)
            else:
                data.append(Scatter3d(
                    x = ring[0],
                    y = ring[1],
                    z = ring[2],
                    mode = 'lines',
                    opacity = .3,
                    line = dict(
                        color = ("rgb(%s,%s,%s)" % tuple([int(x*255) for x in color])),
                        width = 3)
                ))

        curves = [curve[:iterations] for curve in self.curves]
        for curve in curves:
            if engine == 'visvis':
                vv.plot(*curve, lc='k', mw=0, lw=2)
            elif engine == 'pyplot':
                ax.plot(*curve, c=(0, 0, 0, .8))
            else:
                data.append(Scatter3d(
                x = curve[0],
                y = curve[1],
                z = curve[2],
                mode = 'lines',
                line = dict(
                    color = ("rgb(0, 0, 0)"),
                    width = 4)
                ))

        if engine == 'visvis':
            ax = vv.gca()
            app.Run()

        elif engine == 'pyplot':
            fig.tight_layout()
            # plt.draw()
            mng = plt.get_current_fig_manager()
            mng.full_screen_toggle()
            plt.show()

        else:
            fig = Figure(data=data, layout=layout)
            # pl.plot(fig, filename='3d-scatter-with-axes-titles')
            pl.offline.plot(fig)

        return
예제 #43
0
    pass

try:
    import matplotlib
    matplotlib.interactive(True)
    matplotlib.use('WXAgg')
    import rtlsdr  # @UnusedImport
    import wx  # @UnusedImport
except ImportError as error:
    print 'Import error: {}'.format(error)
    input('\nError importing libraries\nPress [Return] to exit')
    exit(1)

try:
    import visvis as vv
    vv.use('wx')
except ImportError:
    pass

import argparse
import multiprocessing
import os.path

from cli import Cli
from constants import APP_NAME
from file import File
from main_window import FrameMain, RtlSdrScanner
from misc import set_version_timestamp


def __init_worker():
예제 #44
0
__author__ = "Mathew Cosgrove"
__copyright__ = ""
__license__ = ""
__version__ = "0.0.1"
__maintainer__ = "Mathew Cosgrove"
__email__ = "*****@*****.**"
__status__ = "Development"

from collections import deque

import numpy as np
from PyQt4 import QtGui

import visvis as vv
backend = 'pyqt4'
vv_app = vv.use(backend)


class VisBaseCanvas(QtGui.QWidget):
    """docstring for VisCanvas"""
    def __init__(self, parent):
        if parent is not None:
            super(VisBaseCanvas, self).__init__()
            # Setup figure to attach to the QtApp
            Figure = vv_app.GetFigureClass()

            self.fig = Figure(parent)
            self.fig.bgcolor = 0.1953, 0.1953, 0.1953

            self.layout = QtGui.QHBoxLayout(parent)
            self.layout.addWidget(self.fig._widget)
예제 #45
0
    already loaded. If not, visvis tries to load the 
    vv.settings.preferredBackend first.
    
    Note: the backend can be changed even when figures are created with
    another backend, but this is not recommended.
    
    Example embedding in Qt4
    ------------------------
    # Near the end of the script:
    
    # Get app instance and create native app
    app = vv.use('pyside')
    app.Create() 
    
    # Create window
    m = MainWindow()
    m.resize(560, 420)
    m.show()
    
    # Run main loop
    app.Run()
    
    """
    return vv.backends.use(backendName)

if __name__=='__main__':
    app = vv.use() # No arg provided: select backend automatically
    print('Selected backend is %s.' % app.GetBackendName())
    app.Create() # Create the backend's application
    app.Run() # Enter the backend's mainloop (not in interactive mode)
    
예제 #46
0
__author__ = "Mathew Cosgrove"
__copyright__ = ""
__license__ = ""
__version__ = "0.0.1"
__maintainer__ = "Mathew Cosgrove"
__email__ = "*****@*****.**"
__status__ = "Development"

from collections import deque

import numpy as np
from PyQt4 import QtGui

import visvis as vv
backend = 'pyqt4'
vv_app = vv.use(backend)


class VisBaseCanvas(QtGui.QWidget):

  """docstring for VisCanvas"""

  def __init__(self, parent):
    if parent is not None:
      super(VisBaseCanvas, self).__init__()
      # Setup figure to attach to the QtApp
      Figure = vv_app.GetFigureClass()

      self.fig = Figure(parent)
      self.fig.bgcolor = 0.1953, 0.1953, 0.1953
예제 #47
0
#!/usr/bin/env python
""" 
This example illustrates embedding a visvis figure in a Qt application.
"""

from PyQt4 import QtGui, QtCore
import visvis as vv

# Create a visvis app instance, which wraps a qt4 application object.
# This needs to be done *before* instantiating the main window. 
app = vv.use('qt4')

class MainWindow(QtGui.QWidget):
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        
        # Make a panel with a button
        self.panel = QtGui.QWidget(self)
        but = QtGui.QPushButton(self.panel)
        but.setText('Push me')
        
        # Make figure using "self" as a parent
        self.fig = vv.backends.backend_qt4.Figure(self)
        
        # Make sizer and embed stuff
        self.sizer = QtGui.QHBoxLayout(self)
        self.sizer.addWidget(self.panel, 1)
        self.sizer.addWidget(self.fig._widget, 2)
        
        # Make callback
        but.pressed.connect(self._Plot)
예제 #48
0
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import sys

import wx

from events import post_event, EventThread, Event

vvPresent = False
if not hasattr(sys, 'frozen'):
    try:
        import visvis as vv
        from visvis.core.line import Line
        app = vv.use('wx')
        vvPresent = True
    except ImportError:
        pass


class PlotterPreview(object):
    def __init__(self, notify, figure, settings):
        self.notify = notify
        self.figure = figure
        self.settings = settings
        self.axes = None
        self.window = None
        self.preview = None

        self.__setup_plot()
예제 #49
0
from PyQt4 import QtGui, QtCore
import numpy as np
import visvis as vv

app = vv.use("pyqt4")


class PlotHandler(object):
    def __init__(self, parent):
        Figure = app.GetFigureClass()
        self.figure = Figure(parent)
        # init plot
        self.axes = vv.subplot(111)
        # self.axes.axisType = "polar"
        self.activePlot = None

    def get_widget(self):
        return self.figure._widget

    def updatePlot(self, X, Y, Z):
        self.activePlot = (X,Y,Z)
        x, y = np.meshgrid(X,Y)
        vv.clf()
        surface = vv.surf(x,y,Z)
        surface.colormap = vv.CM_HOT

    def updateSpecimens(self, data):
        pass
예제 #50
0
		boxsizer.Add (wx.StaticText(self.panel), flag=wx.EXPAND, border=5)
		
		# Save settings
		boxsizer.Add( self.CreateSaveSettingsButton(), flag=wx.EXPAND, border=5)
		# Load settings
		boxsizer.Add( self.CreateLoadSettingsButton(), flag=wx.EXPAND, border=5)
		
		sizer.Add(boxsizer, pos=(1, 0), span=(1, 1), flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT|wx.GROW, border=10)
		########################### End of constructing panel ######################################
		self.panel.SetSizer (sizer)
		
		############################# Setting visvis #######################################
		Figure = app.GetFigureClass()
		self.fig = Figure(self)
		
		boxsizer = wx.BoxSizer (wx.HORIZONTAL)
		boxsizer.Add(self.panel, 0.5, wx.EXPAND)
		boxsizer.Add(self.fig._widget, 2, wx.EXPAND)
		
		#########################################################################################			
		self.SetSizer (boxsizer)
		self.SetAutoLayout(True)
		self.Layout() 
		
#########################################################################

if __name__ == '__main__' :
	app = visvis.use('wx')
	app.Create()
	ODDExperiment (None)
	app.Run()
예제 #51
0
t_end = 3600
epsilon = 1E-10
diff = epsilon  * 2
zeros = np.zeros(Ci.shape)
while(t <= t_end and diff >= epsilon):
    #solve for the gradients in each direction
    l_xyz = ndimage.convolve(Ci, l, mode = "constant",
                           cval = c_out)
#    l_y = ndimage.convolve(Ci, ly, mode = "constant",
#                           cval = c_out)
#    l_z = ndimage.convolve(Ci, lz, mode = "constant",
#                           cval = c_out)
    #first diffusion
    C = Ci + (l_xyz)*D*dt
    #MUST BE normalized by unit VOLUME
    temp_sink = (-sink*dt) / grid_vol
    temp_source = source*dt / grid_vol
    C += temp_sink + temp_source
    #get the summed difference
    diff = np.sum(np.abs(Ci - C))
    #make sure its positive
    C = C * (C > 0.0)
    #update the old
    Ci = C
    #update the time step
    t += dt

vv.use('qt4')    
vv.volshow3(C)
app = vv.use()
app.Run()
예제 #52
0
        boxsizer.Add(self.CreateLoadSettingsButton(), flag=wx.EXPAND, border=5)

        sizer.Add(boxsizer,
                  pos=(1, 0),
                  span=(1, 1),
                  flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT | wx.GROW,
                  border=10)
        ########################### End of constructing panel ######################################
        self.panel.SetSizer(sizer)

        ############################# Setting visvis #######################################
        Figure = app.GetFigureClass()
        self.fig = Figure(self)

        boxsizer = wx.BoxSizer(wx.HORIZONTAL)
        boxsizer.Add(self.panel, 0.5, wx.EXPAND)
        boxsizer.Add(self.fig._widget, 2, wx.EXPAND)

        #########################################################################################
        self.SetSizer(boxsizer)
        self.SetAutoLayout(True)
        self.Layout()


#########################################################################

if __name__ == '__main__':
    app = visvis.use('wx')
    app.Create()
    ODDExperiment(None)
    app.Run()
 def refresh(self):
     vv.figure(self._fig.nr)
     self._app = vv.use()
     self.paint(vv)
예제 #54
0
def show_and_wait():
    """Show visvis windows and enter application loop."""
    global globalVisVisApp
    globalVisVisApp = vv.use()
    globalVisVisApp.Create()
    globalVisVisApp.Run()
예제 #55
0
 def __init__(self, kinfile, audiofile, config, parent = None):
     """
     Data Controller class receives a kinematic file, and an audiofile, and
     sets them up to be played synchronously using the visvis Figure().  
     
     The LCDTimer is passed the time and updated regularly to display the current
     time values that are playing in the audio and in the kinematic data.  
     The data controls are setup on top with the LCD timer, with the figure below.
     The dataController supports switching views, stopping, pausing, rewinding,
     fast forwarding, playing, etc.  It's purdy neat.
     """
     super(DataController, self).__init__(parent)
     backend = 'pyqt4'
     app = vv.use(backend)
     self.fileLoaded = False
     #Set up the buttons for the player
     self.playPauseButton = self.createButton(':/play.svg',50,44)
     self.stopButton = self.createButton(':/stop.svg',40,34)
     self.ffButton = self.createButton(":/fastForward.svg",30,24)
     self.stepForwardButton = self.createButton(":/skipForward.svg",40,34)
     self.stepBackwardButton = self.createButton(":/skipBackward.svg",40,34)
     self.rewindButton = self.createButton(":/rewind.svg",30,24)
     
     self.config= config
     self.fs = self.config[0]
     self.numSensors = self.config[1]
     self.sensorDataFormat = [(14+9*i,21+9*i, self.config[2][i], self.config[3][i]) for i in range(self.numSensors)]
     print self.sensorDataFormat
     
     Figure = app.GetFigureClass()
     self.setMinimumSize(750,700)
     self.resize(750,700)
     self.fig= Figure(self)
     self.fig.enableUserInteraction = False
     self.fig._widget.setMinimumSize(400,280)
     self.spectrogram = specWidget.SpecWidget()
     self.spectrogram.setMinimumSize(400, 150)
     
     self.lcdTimer = lcd.LcdTimer()
     self.lcdTimer.setMaximumHeight(60)
     self.lcdTimer.setMinimumWidth(100)
     
     self.dataViewers = [sdv.SensorDataWidget() for i in xrange(self.numSensors)];
     
     playerLayout = QtGui.QHBoxLayout()
     playerLayout.addStretch()
     playerLayout.addWidget(self.rewindButton)
     playerLayout.addWidget(self.stepBackwardButton)
     playerLayout.addWidget(self.playPauseButton)
     playerLayout.addWidget(self.stopButton)
     playerLayout.addWidget(self.stepForwardButton)
     playerLayout.addWidget(self.ffButton)
     playerLayout.addWidget(self.lcdTimer)
     
     playerGroup = QtGui.QGroupBox("Data Controls")
     playerGroup.setLayout(playerLayout)
     playerGroup.setMaximumHeight(100)
     
     centerLayout= QtGui.QVBoxLayout()
     centerLayout.addWidget(playerGroup)
     centerLayout.addWidget(self.fig._widget)
     centerLayout.addWidget(self.spectrogram)
     
     finalLayout = QtGui.QHBoxLayout()
     finalLayout.addLayout(centerLayout)
     dataLayout = QtGui.QVBoxLayout()
     
     for DV in self.dataViewers:
         dataLayout.addWidget(DV)
     
     finalLayout.addLayout(dataLayout)
     self.setLayout(finalLayout)
     
     self.connect(self.playPauseButton,QtCore.SIGNAL("clicked()"),self.playPause)
     self.connect(self.stopButton,QtCore.SIGNAL("clicked()"),self.stop) 
     self.connect(self.ffButton,QtCore.SIGNAL("pressed()"),self.fastForward)
     self.connect(self.rewindButton, QtCore.SIGNAL("pressed()"),self.rewind)
     self.connect(self.stepForwardButton,QtCore.SIGNAL("pressed()"),self.stepForward)
     self.connect(self.stepBackwardButton,QtCore.SIGNAL("pressed()"),self.stepBackward)
     self.connect(self.spectrogram,QtCore.SIGNAL("pauseGUI()"),self.stepBackward)      
     self.connect(self.spectrogram,QtCore.SIGNAL("newInterval(PyQt_PyObject)"), self.setNewInterval)
     
     self.playing,self.paused,self.stopped = range(3)
     self.status = self.stopped
     self.timer = vv.Timer(self)
     self.timer.Bind(self.onTimer)
     self.timer.nolag = True
     self.disableButtons()
     if((kinfile is not None) and (audiofile is  not None)):
         self.onFileLoaded(kinfile,audiofile)            
예제 #56
0
This example illustrates embedding a visvis figure in a Qt application.
This example works for the pyqt4 and pyside backends.
"""

try:
    from PySide import QtGui, QtCore
    backend = 'pyside'
except ImportError:
    from PyQt4 import QtGui, QtCore
    backend = 'pyqt4'

import visvis as vv

# Create a visvis app instance, which wraps a qt4 application object.
# This needs to be done *before* instantiating the main window. 
app = vv.use(backend)

class MainWindow(QtGui.QWidget):
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        
        # Make a panel with a button
        self.panel = QtGui.QWidget(self)
        but = QtGui.QPushButton(self.panel)
        but.setText('Push me')
        
        # Make figure using "self" as a parent
        Figure = app.GetFigureClass()
        self.fig = Figure(self)
        
        # Make sizer and embed stuff
예제 #57
0
    vvt[i] = sum(cc)

# Interpolate (0 means Cardinal with tension 0)
samples = np.arange(0,len(data)-1,0.05, dtype=np.float32) 
values1 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 'linear')
values2 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 'basis')
values3 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 0)  


# Visualize
fig = vv.figure(1); vv.clf()
fig.position = 57.00, 45.00,  948.00, 969.00

vv.subplot(211)
vv.title('The basis functions for the %s spline' % type)
vv.plot(tt, vv0, lc='r')
vv.plot(tt, vv1, lc='g')
vv.plot(tt, vv2, lc='b')
vv.plot(tt, vv3, lc='m')
vv.plot(tt, vvt, lc='k', ls='--')

vv.subplot(212)
vv.plot(range(len(data)), data, ms='.', ls='')
vv.plot(samples, values1, lc='r')
vv.plot(samples, values2, lc='g')
vv.plot(samples, values3, lc='b', lw=3)
a = vv.gca()
a.legend = 'data', 'Linear', 'Basis', 'Cardinal'

vv.use().Run()
예제 #58
0
#!/usr/bin/env python
"""
This example illustrates embedding a visvis figure in a GTK application.
"""

import gtk
import visvis as vv

app = vv.use('gtk')

class MainWindow(gtk.Window):
    
    def __init__(self, size=(560, 420)):
        gtk.Window.__init__(self)
        
        # Create boxes and button
        hbox = gtk.HBox()
        self.add(hbox)
        vbox = gtk.VBox()
        hbox.pack_start(vbox, False, False, 0)
        button = gtk.Button('Click me')
        vbox.pack_start(button, False, False, 0)
        
        # Cteate visvis figure
        Figure = app.GetFigureClass()
        self.figure = Figure()
        hbox.pack_start(self.figure._widget, True, True, 0)
        
        # Connect signals
        button.connect('clicked', self._Plot)
        self.connect('delete_event', gtk.main_quit)
예제 #59
-1
def main():

    reqlog = logging.getLogger('requests')
    reqlog.setLevel(logging.ERROR)
    log = logging.getLogger(__name__)

    server = subprocess.Popen([sys.executable, '../dora/server/server.py'])
    time.sleep(5)

    # Set up a sampling problem:
    target_samples = 100
    n_train = 20
    lower = [1., 1.]
    upper = [3., 3.]
    acq_name = 'prod_max'

    initialiseArgs = {
        'lower': lower,
        'upper': upper,
        'acq_name': acq_name,
        'n_train': n_train
    }

    # Initialise the sampler
    sampler_info = requests.post('http://localhost:5000/samplers',
                                 json=initialiseArgs).json()
    log.info("Model Info: " + str(sampler_info))

    # Set up plotting:
    plots = {'fig': vv.figure(), 'count': 0, 'shape': (2, 3)}
    plot_triggers = [22, 30, 40, 50, 65, target_samples - 1]

    # Run the active sampling:
    for i in range(target_samples):

        log.info('Iteration: %d' % i)

        # post a request to the sampler for a query location
        req = requests.post(sampler_info['obs_uri'])
        query_loc = req.json()

        # Evaluate the sampler's query on the forward model
        characteristic = np.array(query_loc['query'])
        uid = query_loc['uid']
        uid, measurement = simulate_measurement_vector(characteristic, uid)
        # log.info('Generated measurement ' + measurement.__repr__())

        # Update the sampler with the new observation
        put_response = requests.put(query_loc['uri'],
                                    json=measurement.tolist())

        if i in plot_triggers:
            log.info("Plotting")
            plot_progress(plots, sampler_info)

    print('Finished.')

    vv.use().Run()

    server.terminate()