Ejemplo n.º 1
0
    def _init(self):
        print("Building...")

        self.win = QMainWindow()
        self._default_window_title = self.title

        widget = QWidget()
        self.win.setCentralWidget(widget)

        main_layout = QHBoxLayout()
        widget.setLayout(main_layout)

        main_layout.addWidget(self.slice_widget)
        main_layout.addWidget(self.volume_widget)
        main_layout.addWidget(self.side_widget)

        self.title_reset_timer = Timer(
            interval=2,
            connect=lambda e: self._show_default_window_title(),
            iterations=1,
            start=False)
        self._show_default_window_title()

        self.statusbar = self.win.statusBar()

        self.image_coord_label = QLabel(text="Image Coords")
        self.statusbar.addPermanentWidget(self.image_coord_label)

        self.win.show()
Ejemplo n.º 2
0
    def __init__(self):
        super(Window, self).__init__()
        box = QtGui.QBoxLayout(QtGui.QBoxLayout.LeftToRight, self)
        self.resize(500, 200)
        self.setLayout(box)

        self.canvas_0 = SceneCanvas(bgcolor='w')
        self.vb_0 = ViewBox(parent=self.canvas_0.scene, bgcolor='r')
        self.vb_0.camera.rect = -1, -1, 2, 2
        self.canvas_0.events.initialize.connect(self.on_init)
        self.canvas_0.events.resize.connect(
            partial(on_resize, self.canvas_0, self.vb_0))
        box.addWidget(self.canvas_0.native)

        # pass the context from the first canvas to the second
        self.canvas_1 = SceneCanvas(bgcolor='w', shared=self.canvas_0.context)
        self.vb_1 = ViewBox(parent=self.canvas_1.scene, bgcolor='b')
        self.vb_1.camera.rect = -1, -1, 2, 2
        self.canvas_1.events.resize.connect(
            partial(on_resize, self.canvas_1, self.vb_1))
        box.addWidget(self.canvas_1.native)

        self.tick_count = 0
        self.timer = Timer(interval=1., connect=self.on_timer, start=True)
        self.setWindowTitle('Shared contexts')
        self.show()
Ejemplo n.º 3
0
Archivo: cube.py Proyecto: kod3r/vispy
    def __init__(self):
        self.cube = visuals.Cube((1.0, 0.5, 0.25),
                                 color='red',
                                 edge_color='black')
        self.theta = 0
        self.phi = 0

        SceneCanvas.__init__(self, 'Cube', keys='interactive', size=(400, 400))
        self.cube.transform = transforms.AffineTransform()
        self._timer = Timer('auto', connect=self.on_timer, start=True)
Ejemplo n.º 4
0
    def __init__(self, *args, **kwargs):
        self.cube = CubeVisual(size=(0.8, 0.5, 0.5),
                               color='red',
                               edge_color="k")
        self.theta = 0
        self.phi = 0
        self.cube_transform = transforms.MatrixTransform()
        self.cube.transform = self.cube_transform

        self._timer = Timer('auto', connect=self.on_timer, start=True)
        SceneCanvas.__init__(self, *args, **kwargs)
Ejemplo n.º 5
0
    def _init(self):
        print("Building...")

        self.win = QMainWindow()
        self._default_window_title = self.title

        widget = QWidget()
        self.win.setCentralWidget(widget)

        main_layout = QHBoxLayout()
        widget.setLayout(main_layout)

        main_layout.addWidget(self.slice_widget)
        main_layout.addWidget(self.volume_widget)

        side_layout = QVBoxLayout()
        main_layout.addLayout(side_layout)

        load_image_button = QPushButton("Load Section")
        side_layout.addWidget(load_image_button)
        load_image_button.clicked.connect(self.show_load_image_dialog)

        # Atlas BUttons
        button_hbox = QHBoxLayout()
        side_layout.addLayout(button_hbox)

        atlas_buttons = QButtonGroup(self.win)
        atlas_buttons.setExclusive(True)
        atlas_buttons.buttonToggled.connect(self.atlas_button_toggled)

        for resolution in [100, 25, 10]:
            atlas_button = QPushButton(f"{resolution}um")
            atlas_button.setCheckable(True)
            button_hbox.addWidget(atlas_button)
            atlas_buttons.addButton(atlas_button)

            # The 10um atlas takes way too long to download at the moment.
            # It needs some kind of progress bar or async download feature to be useful.
            # The disabled button here shows it as an option for the future, but keeps it from being used.
            if resolution == 10:
                atlas_button.setDisabled(True)

        self.title_reset_timer = Timer(interval=2, connect=lambda e: self._show_default_window_title(), iterations=1,
                                       start=False)
        self._show_default_window_title()

        self.statusbar = self.win.statusBar()

        self.image_coord_label = QLabel(text="Image Coords")
        self.statusbar.addPermanentWidget(self.image_coord_label)

        self.win.show()
Ejemplo n.º 6
0
    def __init__(self, vertex_shader, fragment_shader_template, functions,
                 *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.vertex_shader = vertex_shader
        self.fragment_shader_template = fragment_shader_template
        self.functions = functions
        self.function_index = 0

        self.program = Program(self.vertex_shader, self.fragment_shader)
        self.program['position'] = [(-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0),
                                    (-1.0, -1.0), (1.0, 1.0), (1.0, -1.0)]
        self.program['resolution'] = self.size
        self.center = array([0.0, 0.0])
        self.program['center'] = array(
            [*unpack_double(self.center[0]), *unpack_double(self.center[1])])
        self.center_min, self.center_max = array([-10.0,
                                                  -10.0]), array([10.0, 10.0])
        self.scale = 2.5
        self.program['scale'] = unpack_double(self.scale)
        self.scale_min, self.scale_max = 10.0**-10.0, 10.0**2.0

        self.line = LinePlotVisual(array([[-10, -10]]), color='white')
        self.position_text = TextVisual('',
                                        color='white',
                                        font_size=10,
                                        anchor_x='right',
                                        anchor_y='top')
        self.iterations_text = TextVisual('',
                                          color='white',
                                          font_size=10,
                                          anchor_x='left',
                                          anchor_y='top')
        self.info_text = TextVisual(self.function_info,
                                    pos=(5, 5),
                                    color='white',
                                    font_size=10,
                                    anchor_x='left',
                                    anchor_y='bottom')

        if use_app().backend_name == 'PyQt5':
            self._backend.leaveEvent = self.on_mouse_exit

        self.timer = Timer(connect=self.update, start=True)
        self.show()
Ejemplo n.º 7
0
def test_application():
    """Test application running"""
    app = use_app()
    print(app)  # __repr__ without app
    app.create()
    wrong = 'glfw' if app.backend_name.lower() != 'glfw' else 'pyqt4'
    assert_raises(RuntimeError, use_app, wrong)
    app.process_events()
    print(app)  # test __repr__

    assert_raises(ValueError, Canvas, keys='foo')
    assert_raises(TypeError, Canvas, keys=dict(escape=1))
    assert_raises(ValueError, Canvas, keys=dict(escape='foo'))  # not an attr

    pos = [0, 0] if app.backend_module.capability['position'] else None
    size = (100, 100)
    # Use "with" statement so failures don't leave open window
    # (and test context manager behavior)
    title = 'default'
    with Canvas(title=title, size=size, app=app, show=True,
                position=pos) as canvas:
        context = canvas.context
        assert_true(canvas.create_native() is None)  # should be done already
        assert_is(canvas.app, app)
        assert_true(canvas.native)
        assert_equal('swap_buffers', canvas.events.draw.callback_refs[-1])

        canvas.measure_fps(0.001)
        sleep(0.002)
        canvas.update()
        app.process_events()
        assert_true(canvas.fps > 0)

        # Other methods
        print(canvas)  # __repr__
        assert_equal(canvas.title, title)
        canvas.title = 'you'
        with use_log_level('warning', record=True, print_msg=False) as l:
            if app.backend_module.capability['position']:
                # todo: disable more tests based on capability
                canvas.position = pos
            canvas.size = size
        if 'ipynb_vnc' in canvas.app.backend_name.lower():
            assert_true(len(l) >= 1)
        else:
            assert_true(len(l) == 0)
        canvas.connect(on_mouse_move)
        assert_raises(ValueError, canvas.connect, _on_mouse_move)
        if sys.platform != 'darwin':  # XXX knownfail, prob. needs warmup
            canvas.show(False)
            canvas.show()
        app.process_events()
        assert_raises(ValueError, canvas.connect, on_nonexist)
        # deprecation of "paint"
        with use_log_level('info', record=True, print_msg=False) as log:
            olderr = sys.stderr
            try:
                fid = StringIO()
                sys.stderr = fid

                @canvas.events.paint.connect
                def fake(event):
                    pass
            finally:
                sys.stderr = olderr
        assert_equal(len(log), 1)
        assert_in('deprecated', log[0])

        # screenshots
        gl.glViewport(0, 0, *size)
        ss = _screenshot()
        assert_array_equal(ss.shape, size + (4,))
        assert_equal(len(canvas._backend._vispy_get_geometry()), 4)
        if sys.platform != 'win32':  # XXX knownfail for windows
            assert_array_equal(canvas.size, size)
        assert_equal(len(canvas.position), 2)  # XXX knawnfail, doesn't "take"

        # GLOO: should have an OpenGL context already, so these should work
        vert = "void main (void) {gl_Position = pos;}"
        frag = "void main (void) {gl_FragColor = pos;}"
        program = Program(vert, frag)
        assert_raises(RuntimeError, program.glir.flush, context.shared.parser)
        
        vert = "uniform vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "uniform vec4 pos;\nvoid main (void) {gl_FragColor = pos;}"
        program = Program(vert, frag)
        #uniform = program.uniforms[0]
        program['pos'] = [1, 2, 3, 4]
        
        vert = "attribute vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "void main (void) {}"
        program = Program(vert, frag)
        #attribute = program.attributes[0]
        program["pos"] = [1, 2, 3, 4]
        
        # use a real program
        program._glir.clear()
        vert = ("uniform mat4 u_model;"
                "attribute vec2 a_position; attribute vec4 a_color;"
                "varying vec4 v_color;"
                "void main (void) {v_color = a_color;"
                "gl_Position = u_model * vec4(a_position, 0.0, 1.0);"
                "v_color = a_color;}")
        frag = "void main() {gl_FragColor = vec4(0, 0, 0, 1);}"
        n, p = 250, 50
        T = np.random.uniform(0, 2 * np.pi, n)
        position = np.zeros((n, 2), dtype=np.float32)
        position[:, 0] = np.cos(T)
        position[:, 1] = np.sin(T)
        color = np.ones((n, 4), dtype=np.float32) * (1, 1, 1, 1)
        data = np.zeros(n * p, [('a_position', np.float32, 2),
                                ('a_color', np.float32, 4)])
        data['a_position'] = np.repeat(position, p, axis=0)
        data['a_color'] = np.repeat(color, p, axis=0)

        program = Program(vert, frag)
        program.bind(VertexBuffer(data))
        program['u_model'] = np.eye(4, dtype=np.float32)
        # different codepath if no call to activate()
        program.draw(gl.GL_POINTS)
        subset = IndexBuffer(np.arange(10, dtype=np.uint32))
        program.draw(gl.GL_POINTS, subset)

        # bad programs
        frag_bad = ("varying vec4 v_colors")  # no semicolon
        program = Program(vert, frag_bad)
        assert_raises(RuntimeError, program.glir.flush, context.shared.parser)
        frag_bad = None  # no fragment code. no main is not always enough
        assert_raises(ValueError, Program, vert, frag_bad)

        # Timer
        timer = Timer(interval=0.001, connect=on_mouse_move, iterations=2,
                      start=True, app=app)
        timer.start()
        timer.interval = 0.002
        assert_equal(timer.interval, 0.002)
        assert_true(timer.running)
        sleep(.003)
        assert_true(timer.elapsed >= 0.002)
        timer.stop()
        assert_true(not timer.running)
        assert_true(timer.native)
        timer.disconnect()

        # test that callbacks take reasonable inputs
        _test_callbacks(canvas)

        # cleanup
        canvas.swap_buffers()
        canvas.update()
        app.process_events()
        # put this in even though __exit__ will call it to make sure we don't
        # have problems calling it multiple times
        canvas.close()  # done by context
Ejemplo n.º 8
0
def _test_application(backend):
    """Test application running"""
    app = Application()
    assert_raises(ValueError, app.use, 'foo')
    app.use(backend)
    wrong = 'Glut' if app.backend_name != 'Glut' else 'Pyglet'
    assert_raises(RuntimeError, app.use, wrong)
    app.process_events()
    if backend is not None:
        # "in" b/c "qt" in "PySide (qt)"
        assert_true(backend in app.backend_name)
    print(app)  # test __repr__

    # Canvas
    pos = [0, 0, 1, 1]
    # Use "with" statement so failures don't leave open window
    # (and test context manager behavior)
    with Canvas(title='me', app=app, show=True, position=pos) as canvas:
        assert_true(canvas.app is app)
        assert_true(canvas.native)
        print(canvas.size >= (1, 1))
        canvas.resize(90, 90)
        canvas.move(1, 1)
        assert_equal(canvas.title, 'me')
        canvas.title = 'you'
        canvas.position = (0, 0)
        canvas.size = (100, 100)
        canvas.connect(on_mouse_move)
        assert_raises(ValueError, canvas.connect, _on_mouse_move)
        canvas.show()
        assert_raises(ValueError, canvas.connect, on_nonexist)

        # screenshots
        ss = _screenshot()
        assert_array_equal(ss.shape[2], 3)  # XXX other dimensions not correct?
        # XXX it would be good to do real checks, but sometimes the
        # repositionings don't "take" (i.e., lead to random errors)
        assert_equal(len(canvas._backend._vispy_get_geometry()), 4)
        assert_equal(len(canvas.size), 2)
        assert_equal(len(canvas.position), 2)

        # GLOO: should have an OpenGL context already, so these should work
        vert = VertexShader("void main (void) {gl_Position = pos;}")
        frag = FragmentShader("void main (void) {gl_FragColor = pos;}")
        program = Program(vert, frag)
        assert_raises(ShaderError, program.activate)

        vert = VertexShader("uniform vec4 pos;"
                            "void main (void) {gl_Position = pos;}")
        frag = FragmentShader("uniform vec4 pos;"
                              "void main (void) {gl_FragColor = pos;}")
        program = Program(vert, frag)
        uniform = program.uniforms[0]
        uniform.set_data([1, 2, 3, 4])
        program.activate()  # should print
        uniform.upload(program)
        program.detach(vert, frag)
        assert_raises(ShaderError, program.detach, vert)
        assert_raises(ShaderError, program.detach, frag)

        vert = VertexShader("attribute vec4 pos;"
                            "void main (void) {gl_Position = pos;}")
        frag = FragmentShader("void main (void) {}")
        program = Program(vert, frag)
        attribute = program.attributes[0]
        attribute.set_data([1, 2, 3, 4])
        program.activate()
        attribute.upload(program)
        # cannot get element count
        assert_raises(ProgramError, program.draw, 'POINTS')

        # use a real program
        vert = ("uniform mat4 u_model;"
                "attribute vec2 a_position; attribute vec4 a_color;"
                "varying vec4 v_color;"
                "void main (void) {v_color = a_color;"
                "gl_Position = u_model * vec4(a_position, 0.0, 1.0);"
                "v_color = a_color;}")
        frag = "void main() {gl_FragColor = vec4(0, 0, 0, 1);}"
        n, p = 250, 50
        T = np.random.uniform(0, 2 * np.pi, n)
        position = np.zeros((n, 2), dtype=np.float32)
        position[:, 0] = np.cos(T)
        position[:, 1] = np.sin(T)
        color = np.ones((n, 4), dtype=np.float32) * (1, 1, 1, 1)
        data = np.zeros(n * p, [('a_position', np.float32, 2),
                                ('a_color', np.float32, 4)])
        data['a_position'] = np.repeat(position, p, axis=0)
        data['a_color'] = np.repeat(color, p, axis=0)

        program = Program(vert, frag)
        program.set_vars(VertexBuffer(data))
        program['u_model'] = np.eye(4, dtype=np.float32)
        program.draw('POINTS')  # different codepath if no call to activate()
        subset = ElementBuffer(np.arange(10, dtype=np.uint32))
        program.draw('POINTS', subset=subset)

        # bad programs
        frag_bad = ("varying vec4 v_colors")  # no semicolon
        program = Program(vert, frag_bad)
        assert_raises(ShaderError, program.activate)
        frag_bad = None  # no fragment code. no main is not always enough
        program = Program(vert, frag_bad)
        assert_raises(ProgramError, program.activate)

        # Timer
        timer = Timer(interval=0.001, connect=on_mouse_move, iterations=2,
                      start=True, app=app)
        timer.start()
        timer.interval = 0.002
        assert_equal(timer.interval, 0.002)
        assert_true(timer.running)
        timer.stop()
        assert_true(not timer.running)
        assert_true(timer.native)
        timer.disconnect()

        # test that callbacks take reasonable inputs
        _test_callbacks(canvas)

        # cleanup
        canvas.swap_buffers()
        canvas.update()
        # put this in even though __exit__ will call it to make sure we don't
        # have problems calling it multiple times
        canvas.close()
    app.quit()
    app.quit()  # make sure it doesn't break if a user does something silly
Ejemplo n.º 9
0
def test_multiple_canvases():
    """Testing multiple canvases"""
    n_check = 3
    app = use_app()
    with Canvas(app=app, size=_win_size, title='same_0') as c0:
        with Canvas(app=app, size=_win_size, title='same_1') as c1:
            ct = [0, 0]

            @c0.events.draw.connect
            def draw0(event):
                ct[0] += 1
                c0.update()

            @c1.events.draw.connect  # noqa, analysis:ignore
            def draw1(event):
                ct[1] += 1
                c1.update()

            c0.show()  # ensure visible
            c1.show()
            c0.update()  # force first draw
            c1.update()

            timeout = time() + 2.0
            while (ct[0] < n_check or ct[1] < n_check) and time() < timeout:
                app.process_events()
            print((ct, n_check))
            assert n_check <= ct[0] <= n_check + 2  # be a bit lenient
            assert n_check <= ct[1] <= n_check + 2

            # check timer
            global timer_ran
            timer_ran = False

            def on_timer(_):
                global timer_ran
                timer_ran = True
            t = Timer(0.1, app=app, connect=on_timer, iterations=1,  # noqa
                      start=True)
            app.process_events()
            sleep(0.5)  # long for slow systems
            app.process_events()
            app.process_events()
            assert timer_ran

    if app.backend_name.lower() == 'wx':
        raise SkipTest('wx fails test #2')  # XXX TODO Fix this

    kwargs = dict(app=app, autoswap=False, size=_win_size,
                  show=True)
    with Canvas(title='0', **kwargs) as c0:
        with Canvas(title='1', **kwargs) as c1:
            bgcolors = [None] * 2

            @c0.events.draw.connect
            def draw00(event):
                print('  {0:7}: {1}'.format('0', bgcolors[0]))
                if bgcolors[0] is not None:
                    gl.glViewport(0, 0, *list(_win_size))
                    gl.glClearColor(*bgcolors[0])
                    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
                    gl.glFinish()

            @c1.events.draw.connect
            def draw11(event):
                print('  {0:7}: {1}'.format('1', bgcolors[1]))
                if bgcolors[1] is not None:
                    gl.glViewport(0, 0, *list(_win_size))
                    gl.glClearColor(*bgcolors[1])
                    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
                    gl.glFinish()

            for ci, canvas in enumerate((c0, c1)):
                print('draw %s' % canvas.title)
                bgcolors[ci] = [0.5, 0.5, 0.5, 1.0]
                _update_process_check(canvas, 127)

            for ci, canvas in enumerate((c0, c1)):
                print('test')
                _update_process_check(canvas, 127, draw=False)
                bgcolors[ci] = [1., 1., 1., 1.]
                _update_process_check(canvas, 255)
                bgcolors[ci] = [0.25, 0.25, 0.25, 0.25]
                _update_process_check(canvas, 64)
Ejemplo n.º 10
0
        print("Volume render method: %s" % method)
        cmap = opaque_cmap if method in ['mip', 'iso'] else translucent_cmap
        volume1.method = method
        volume1.cmap = cmap
        volume2.method = method
        volume2.cmap = cmap
    elif event.text == '3':
        volume1.visible = not volume1.visible
        volume2.visible = not volume1.visible
    elif event.text == '4':
        if volume1.method in ['mip', 'iso']:
            cmap = opaque_cmap = next(opaque_cmaps)
        else:
            cmap = translucent_cmap = next(translucent_cmaps)
        volume1.cmap = cmap
        volume2.cmap = cmap
    elif event.text != '' and event.text in '[]':
        s = -0.025 if event.text == '[' else 0.025
        volume1.threshold += s
        volume2.threshold += s
        th = volume1.threshold if volume1.visible else volume2.threshold
        print("Isosurface threshold: %0.3f" % th)


timer = Timer('auto', connect=on_timer, start=True)

canvas.show()
if __name__ == '__main__' and sys.flags.interactive == 0:
    if sys.flags.interactive != 1:
        canvas.app.run()
Ejemplo n.º 11
0
scene.add_to_subplot(source_object,
                     row=0,
                     col=0,
                     title='Project iEEG data',
                     **KW)
scene.add_to_subplot(brain_obj, row=0, col=0, rotate='left', use_this_cam=True)

# Finally, add the colorbar :
colorbar = ColorbarObj(source_object,
                       cblabel='Projection of niEEG data',
                       **CBAR_STATE)
scene.add_to_subplot(colorbar, row=0, col=1, width_max=200, rotate='up')

# Animation

app_timer = Timer(app=CONFIG['VISPY_APP'], interval='auto', iterations=-1)


def on_timer(*args, **kwargs):
    if hasattr(brain_obj, 'camera'):
        brain_obj.camera.azimuth += 1
        t = app_timer.elapsed
        frame = int(np.floor(t * sampling_frequency))

        new_data = data[:, frame % data.shape[1]].ravel()
        source_object._data = vispy_array(new_data)
        source_object.update()
        source_object.project_sources(brain_obj)
        source_object.color_sources()

Ejemplo n.º 12
0
# Create app
meshApp = MeshApp3D(root)
meshApp.view.camera.center = [1.5, 0.0, 0.0]
meshApp.mesh.light._pos = [1.5, 0.0, 0.0]

# Define translation function
t0 = default_timer()


def translateMesh(translation):
    for triangleIndex in range(len(root._vertices)):
        for componentIndex, displacementComponent in enumerate(translation):
            root._vertices[triangleIndex][
                componentIndex] = displacementComponent


def on_timer(event):
    t = default_timer() - t0
    translation = [-np.sin(t), np.cos(t), 0.0]
    translateMesh(translation)
    print(root.get_vertices(indexed="faces")[0][0])
    meshApp.mesh._vertexBuffer.set_subdata(np.array(
        root.get_vertices(indexed="faces"), dtype=np.float32),
                                           offset=0)
    meshApp.mesh.update()


timer = Timer(interval='auto', connect=on_timer, start='true')

# Run app
meshApp.run()